1

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?

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

import re

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

This outputs:

['5']

4 Comments

that printed out [] on Python 3.10 for me.
@JLPeyret He/She should've used rf"" instead of f"" because of that \b.
hehe. I also cribbed rf"\b" from them after my "\b" failed ;-)
Oops, fixed. :)
1

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

2 Comments

Even if there is no re.compile, the re module will automatically compile for us. It encapsulates _compile() function.
Yes, hence my remark about the perf gains not necessarily being not that helpful. I think I started using re on Python versions before that got cached. On closer look, my answer is similar to ldyer's which I upvoted. Mostly because I only saw the str(number) initially in that answer, before writing this.

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.