python正则表达式搜索限制

时间:2018-11-19 13:53:00

标签: regex python-2.7

我有以下情况

重新导入

target_regex ='^(?! P- [5678])。*' 模式= re.compile(target_regex,re.IGNORECASE)

mylists = ['p-1.1','P-5']

target_object_is_found = pattern.findall(''。join(mylists))

打印“ target_object_is_found:”,target_object_is_found


这将给

target_object_is_found:['P-1.1P-5']

但是从我的正则表达式中,我需要的是仅P-1.1即可消除P-5

1 个答案:

答案 0 :(得分:1)

join添加了mylist中的项目,并且P-5不再位于字符串的开头。

您可以使用

import re

target_regex = 'P-[5-8]'
pattern = re.compile(target_regex, re.IGNORECASE)
mylists=['p-1.1', 'P-5']
target_object_is_found = [x for x in mylists if not pattern.match(x)]
print("target_object_is_found: {}".format(target_object_is_found))
# => target_object_is_found: ['p-1.1']

请参见Python demo

这里,P-[5-8]模式是用re.IGNORECASE标志编译的,用于检查{{1}中mylist(请参阅[...]列表理解)内的每个项目}}方法,仅在字符串的开头查找匹配项。匹配结果相反,请参见regex_objext.match之后的not

因此,将返回所有不以if模式开头的项目。