Tuesday, 7 August 2018

Python user input as regular expression, how to do it correctly?

I'm using Python 3. In my application, the use can input a regular expression string directly and the application will use it to match some strings. For example the user can type \t+. However I can't make it work as I can't correctly convert it to a correct regular expression. I've tried and below is my code.

>>> import re
>>> re.compile(re.escape("\t+")).findall("  ")
[]

However when I change the regex string to \t, it will work.

>>> re.compile(re.escape("\t")).findall("   ")
['\t']

Note the parameter to findall IS a tab character. I don't know why it seems not correctly displayed in Stackoverflow.

Anyone can point me the right direction to solve this? Thanks.



from Python user input as regular expression, how to do it correctly?

No comments:

Post a Comment