Home > Back-end >  How to dynamically generate a regular expression in python?
How to dynamically generate a regular expression in python?

Time:11-11

I have this regular expression r'\b28\b'. In this expression 28 should be dynamic. In other words, 28 is a dynamic value which the user enters. So, instead of 28 it can have 5. In that case, the expression would be r'\b5\b'.

I tried the below two approaches but they are not working.

  1. r"r'\b" room_number r"\b'"
  2. "r'\b" room_number "\b'"

I want to know how can I do it? Can someone please help me with it?

CodePudding user response:

Contrary to the previous answer, you should generally use r for regular expression strings. But the way you had it, the r was inside the strings. It needs to go outside. It would look like this:

regex = r"\b"   str(my_var)   r"\b"

but in general it's nicer to use raw f-strings. This way you don't have to convert the int to a str yourself:

regex = rf"\b{my_var}\b"

Try running the following to see that it works:

import re

str_to_match = '3 45 72 3 45'
my_var = 45

regex = rf"\b{my_var}\b"

for f in re.findall(regex, str_to_match):
    print(f)

Outputs:

45
45

CodePudding user response:

You can use a format string with re.escape, which will escape special characters for you:

import re

room_number = 5
reg_expr = f"\b{re.escape(str(room_number))}\b"
re.findall(reg_expr, "Room 5 is the target room.")

This outputs:

['5']

CodePudding user response:

Well, if you are like me, I always pre-compile regexes.

(Not sure it always improves performance much, but I just find it a drag to remember both the compiled and the non-compiled syntax, so I picked using only the compiled.)

That solves your problem with f-strings:

import re

data = """
Look for 28
Look for 42
"""

target = 28
patre = re.compile(rf"\b{target}\b")


for line in data.splitlines():
    if patre.search(line):
        print(line)

output:

Look for 28
  • Related