2

I have seen several related posts and several forums to find an answer for my question, but nothing has come up to what I need.

I am trying to use variable instead of hard-coded values in regex which search for either word in a line.

However i am able to get desired result if i don't use variable.

<http://www.somesite.com/software/sub/a1#Msoffice>
<http://www.somesite.com/software/sub1/a1#vlc>
<http://www.somesite.com/software/sub2/a2#dell>
<http://www.somesite.com/software/sub3/a3#Notepad>

re.search(r"\#Msoffice|#vlc|#Notepad", line)

This regex will return the line which has #Msoffice OR #vlc OR #Notepad.

I tried defining a single variable using re.escape and that worked absolutely fine. However i have tried many combination using | and , (pipe and comma) but no success.

Is there any way i can specify #Msoffice , #vlc and #Notepad in different variables and so later i can change those ?

Thanks in advance!!

2 Answers 2

1

If I did understand you the right way you'd like to insert variables in your regex.

You are actually using a raw string using r' ' to make the regex more readable, but if you're using f' ' it allows you to insert any variables using {your_var} then construct your regex as you like:

var1 = '#Msoffice'
var2 = '#vlc'
var3 = '#Notepad'

re.search(f'{var1}|{var2}|{var3}', line)

The most annoying issue is that you will have to add \ to escaped char, to look for \ it will be \\

Hope it helped

Sign up to request clarification or add additional context in comments.

Comments

0
import re

lines = ["<http://www.somesite.com/software/sub/a1#Msoffice>", 
                "<http://www.somesite.com/software/sub1/a1#vlc>",
                "<http://www.somesite.com/software/sub2/a2#dell>",
                "<http://www.somesite.com/software/sub3/a3#Notepad>"]

for line in lines:
    if re.search(r'\b(?:\#{}|\#{}|\#{})\b'.format('Msoffice', 'vlc', 'Notepad'), line): 
        print(line)

Output :

<http://www.somesite.com/software/sub/a1#Msoffice>
<http://www.somesite.com/software/sub1/a1#vlc>
<http://www.somesite.com/software/sub3/a3#Notepad>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.