[英]Multiple Regular expression in one line
list_num=['AYSGS11458630001111252','1234567','LUPUP003164311E0111644','ABCGFD','AFC123A']
对于上面的 list_num 我想写 RE,它给出如下。
预期输出
AYSGS11458630001111252
none
LUPUP003164311E0111644
none
none
输出应该是列表中的两个项目
我已经在网上写了请纠正并建议我。
re.match((r"^(([A-Z]{5}[0-9]{17})|([A-Z]{5}[0-9]{9}[A-Z]{1}[0-9]{7}))$", list_num)
re.match(pattern, string, flags=0)
定义为return re.compile(pattern, flags).match(string)
它不能处理字符串列表而不是字符串,但这很容易用循环修复. 但是由于我们要多次运行同一个表达式,最好编译一次,而不是在循环内重复编译。
这就是我会做的:
import re
list_num=['AYSGS11458630001111252','1234567','LUPUP003164311E0111644','ABCGFD','AFC123A']
pattern = r"^(([A-Z]{5}[0-9]{17})|([A-Z]{5}[0-9]{9}[A-Z]{1}[0-9]{7}))$"
compiled_pattern = re.compile(pattern)
for m in map(compiled_pattern.match, list_num):
#you could also use pattern.fullmatch, and not enclose your pattern with ^ and $
if m is not None:
print(m.string)
else:
print(m)
## shows:
##AYSGS11458630001111252
##None
##LUPUP003164311E0111644
##None
##None
或者这个:
x = [m.string if isinstance(m, re.Match) else m
for m in map(compiled_pattern.match, list_num)]
print (x)
#['AYSGS11458630001111252', None, 'LUPUP003164311E0111644', None, None]
'or even this:'
def multi_match(pattern, seq):
compiled_pattern=re.compile(pattern)
return [m.string if isinstance(m, re.Match) else m
for m in map(compiled_pattern.match, list_num)]
print(multi_match(pattern, list_num))
#['AYSGS11458630001111252', None, 'LUPUP003164311E0111644', None, None]
或者,如果不需要保留索引位置,例如:
def filter_match(pattern, seq):
compiled_pattern=re.compile(pattern)
return list(filter(
lambda line: compiled_pattern.match(line) is not None,
list_num))
print(filter_match(pattern, list_num))
#['AYSGS11458630001111252', 'LUPUP003164311E0111644']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.