[英]python regular expression does not return the value as expected
I only need to print out the non-match item which "333-33".我只需要打印出“333-33”的不匹配项。 When I run the following code, it prints all the items such as "111-11", "222-22", "333-33"...
当我运行以下代码时,它会打印所有项目,例如“111-11”、“222-22”、“333-33”......
"333-33" should return the None type... "333-33" 应该返回 None 类型...
Any suggestions?有什么建议么? Thank you very much in advance.
非常感谢您提前。
ALLOW_LIST = ["(4[0-4]{2})-\d{2}", "111-11", "222-22"]
item=[]
codes = ["111-11", "222-22", "333-33"]
for code in codes:
for i in ALLOW_LIST:
if re.search(i, code) is None:
item.append(code)
print(item)
You can use the all
function with a generator expression that iterates through ALLOW_LIST
to ensure that none of the patterns matches the current code
before outputting it:您可以将
all
function 与生成器表达式一起使用,该表达式遍历ALLOW_LIST
以确保在输出之前没有任何模式与当前code
匹配:
[code for code in codes if all(not re.search(i, code) for i in ALLOW_LIST)]
From what I understand you want to include only items matched by allow list.据我了解,您只想包含与允许列表匹配的项目。
Your if statement will append items that are not matched : if re.search(i, code) is None:
您的 if 语句将 append 项目不匹配:
if re.search(i, code) is None:
You should edit out your if statement to include items that are matched:您应该编辑您的 if 语句以包含匹配的项目:
ALLOW_LIST = ["(4[0-4]{2})-\d{2}", "111-11", "222-22"]
item=[]
codes = ["111-11", "222-22", "333-33"]
for code in codes:
for i in ALLOW_LIST:
if re.search(i, code):
item.append(code)
print(item)
You could form a single regex alternation here:你可以在这里形成一个单一的正则表达式交替:
ALLOW_LIST = ["4[0-4]{2}-\d{2}", "111-11", "222-22"]
regex = r'^(?:' + '|'.join(ALLOW_LIST) + r')$'
items = []
codes = ["111-11", "222-22", "333-33"]
for code in codes:
if not re.search(regex, code):
items.append(code)
print(items) # ['333-33']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.