我有以下列表,我正在尝试使用正则表达式提取项目型号
names=[
'Honda Engine GX200 6.5HP 2.43" x 3/4" Crankshaft',
'Honda New GX390 Engine Standard 1" Crank, Electric Start, Oil Alert',
'Genuine Honda 79160-SHJ-A41 Temperature Driver Motor Assembly',
'Auto Express Long Block Engine Crankcase with Cylinder Head Valves Fits Honda GX200 6.5 HP',
'Honda 08207-10W30 PK2 Motor Oil'
]
型号只能包含大写字母,-,数字
for name in names:
model_num=re.search('([A-Z]+\d+\-[A-Z]*)',name).groups()[0]
我的正则表达式不是一直都在工作。预期输出为:
['GX200','GX390','79160-SHJ-A41','GX200','08207-10W30']
如果有比regex更简单的方法起作用,那么任何帮助都将不胜感激。
最佳答案
使用re.compile
可以提高速度:
find_model = re.compile(
"""
[A-Z\d\-]+
(?![a-z]) # Check that next char isn't lowercase to avoid getting false-positive head letter only
""",
re.VERBOSE,
)
for name in names:
result = find_model.search(name)
if result:
model_num = result.group(0)
print(model_num)
关于python - 使用正则表达式查找型号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60436885/