使用正则表达式查找型号

2024-09-29 07:24:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的列表,我正在尝试使用regex提取项目型号

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更简单的方法也能奏效的话,任何帮助都是非常感谢的


Tags: 项目name列表namesengineregexhpoil
1条回答
网友
1楼 · 发布于 2024-09-29 07:24:43

使用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)

相关问题 更多 >