我有以下情况
import re
target_regex = '^(?!P\-[5678]).*'
pattern = re.compile(target_regex, re.IGNORECASE)
mylists=['p-1.1', 'P-5']
target_object_is_found = pattern.findall(''.join(mylists))
print "target_object_is_found:", target_object_is_found这会给
target_object_is_found: ['P-1.1P-5']但从我的判断来看,我需要的仅仅是P-1.1就消除了P-5
发布于 2018-11-19 13:57:44
您在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演示。
在这里,使用P-[5-8]标志编译re.IGNORECASE模式,并使用regex_objext.match方法检查mylist中的每个项(请参阅[...]列表理解),该方法仅在字符串的开头查找匹配项。匹配结果是相反的,请参阅not后面的if。
因此,返回不以(?i)P-[5-8]模式开头的所有项。
https://stackoverflow.com/questions/53376120
复制相似问题