在编译regexes时,是否有一种转换元字符编译或使用的方法?当前的代码如下所示:
当前代码:
import re
the_value = '192.168.1.1'
the_regex = re.compile(the_value)
my_collection = ['192a168b1c1', '192.168.1.1']
my_collection.find_matching(the_regex)
result = ['192a168b1c1', '192.168.1.1']理想的解决方案将类似于
import re
the_value = '192.168.1.1'
the_regex = re.compile(the_value, use_metacharacters=False)
my_collection = ['192a168b1c1', '192.168.1.1']
my_collection.find_matching(the_regex)
result = ['192.168.1.1']理想的解决方案是让re库处理元字符的禁用,以避免尽可能多地参与这个过程。
发布于 2013-11-22 02:37:43
不是的。然而:
the_regex = re.compile(re.escape(the_value))发布于 2013-11-22 03:15:18
为此使用re.escape()函数。
返回带有所有非字母数字反斜杠的字符串;如果要匹配可能包含正则表达式元字符的任意文字字符串,这是非常有用的。
>>> import re
>>> re.escape('192.168.1.1')
'192\\.168\\.1\\.1'https://stackoverflow.com/questions/20135953
复制相似问题