如何为 r.match 转义 rethinkdb 正则表达式模式 [英] How to escape rethinkdb regex pattern for r.match

查看:44
本文介绍了如何为 r.match 转义 rethinkdb 正则表达式模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用用户输入在 rethinkdb 中使用 r.match 进行搜索 - 整个用户输入应被视为搜索模式.我正在根据这样的用户输入创建正则表达式:

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:

正则表达式.*(?i)\u0141[.*中的错误(部分[.*):缺少]:[.* in:

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

有没有办法为 rethinkdb 转义正则表达式?我曾尝试使用 python re.escape,但是将 unicode 与这样的错误结合使用时失败了:

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:

正则表达式错误 .*(?i)\\u0141.*(部分 \\u0141):转义序列无效:\u0141

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

有什么建议吗?

推荐答案

为此使用 re.escape() 函数:

re 转义

转义(字符串)

返回所有非字母数字反斜杠的字符串;如果您想匹配可能包含正则表达式元字符的任意文字字符串,这将非常有用.

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.

这篇关于如何为 r.match 转义 rethinkdb 正则表达式模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆