是否有一种简单的方法可以在Python正则表达式中使用和忽略元字符?

时间:2013-11-22 02:35:37

标签: python regex metacharacters

有没有办法在编译正则表达式时切换编译或使用元字符?当前代码如下所示:


当前代码:

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库处理元字符的禁用,以避免必须尽可能多地参与进程。

2 个答案:

答案 0 :(得分:7)

不。但是:

the_regex  = re.compile(re.escape(the_value))

答案 1 :(得分:6)

使用re.escape()功能。

  

返回字符串,所有非字母数字反向;如果要匹配可能包含正则表达式元字符的任意文字字符串,这非常有用。

>>> import re
>>> re.escape('192.168.1.1')
'192\\.168\\.1\\.1'