How to escape rethinkdb regex pattern for r.match

2019-08-09 11:05发布

问题:

I want to search with r.match in rethinkdb using user input - whole user input should be treated as search pattern. I'm creating regex based on user input like this:

pattern = u'.*(?i){0}.*'.format(user_input)

But if user inputs '[' or ']' or any other special character I got errors from rethink like this:

Error in regexp .*(?i)\u0141[.* (portion [.*): missing ]: [.* in:

Is there any way to escape regex for rethinkdb? I have tried to use python re.escape but this fail when combining unicode with errors like this one:

Error in regexp .*(?i)\\u0141.* (portion \\u0141): invalid escape sequence: \u0141

Any suggestions?

回答1:

Use the re.escape() function for this:

re escape

escape(string)

Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.