Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex python attaching raw to string variables

Tags:

python

regex

Normally you would put an r in front of the string to make it raw, but how to do this with a variable (string)?

This is what I tried so far:

import re
var = "++"
re.search(r"++", "++")      # also does not work
re.search(var, "++")        # fails
re.search(r(var), "++")     # fails
re.search(r + var, "++")    # fails
re.search("r" + var, "++")  # fails
like image 593
PascalVKooten Avatar asked Oct 31 '25 11:10

PascalVKooten


1 Answers

Use the re.escape() function for this.

>>> import re
>>> var = "++"
>>> re.search(re.escape(var), '++')
<_sre.SRE_Match object at 0x02B36B80>
like image 89
hwnd Avatar answered Nov 03 '25 01:11

hwnd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!