You must be careful when inserting strings into a regex pattern.
This is because the string may contain special regular expression characters that can lead to errors or give unexpected results.
To give an example:
>>> import re >>> s = 'one*two*three*four*five' >>> t = '*f' >>> r = re.compile(r'%s\w+' % t) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/re.py", line 190, in compile return _compile(pattern, flags) File "/usr/lib/python2.7/re.py", line 244, in _compile raise error, v
This fails because the inserted string contains * , which is a special regular expression character.
However, this problem can be solved by using the re.escape function in the inserted row:
>>> r = re.compile(r'%s\w+' % re.escape(t)) >>> r.findall(s) ['*four', '*five']
source share