繁体   English   中英

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

[英]Is there a simple way to switch between using and ignoring metacharacters in Python regular expressions?

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


当前代码:

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

不。 然而:

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

使用re.escape()函数。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM