I'd like to use a variable
inside a regex
, how can I do this in Python
?
TEXTO = sys.argv[1]
if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE):
# Successful match
else:
# Match attempt failed
I'd like to use a variable
inside a regex
, how can I do this in Python
?
TEXTO = sys.argv[1]
if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE):
# Successful match
else:
# Match attempt failed
You have to build the regex as a string:
Note the use of
re.escape
so that if your text has special characters, they won't be interpreted as such.I agree with all the above unless:
sys.argv[1]
was something likeChicken\d{2}-\d{2}An\s*important\s*anchor
you would not want to use
re.escape
, because in that case you would like it to behave like a regexI needed to search for usernames that are similar to each other, and what Ned Batchelder said was incredibly helpful. However, I found I had cleaner output when I used re.compile to create my re search term:
Output can be printed using the following:
You can use format keyword as well for this.Format method will replace {} placeholder to the variable which you passed to the format method as an argument.
I find it very convenient to build a regular expression pattern by stringing together multiple smaller patterns.
Output:
This will insert what is in TEXTO into the regex as a string.