python - 使用正则表达式查找型号

标签 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']

如果有比正则表达式更简单的方法也可以使用,我们将不胜感激。

最佳答案

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

相关文章:

python - 有时可以点击按钮,有时却不起作用

python - 如何在 Keras 的函数式 API 中构建以嵌套模型的一层结尾的子模型

python - 压缩文件解压缩时出现 unicode 错误

大写字母的 Java 正则表达式

python - 如何在python中解析带有国际单词的文件

python - 在 Cython 中使用 C 创建的一组列表比纯 Python 慢得多 - 为什么?

c# - 创建一个 Python COM 对象

javascript - 如何正则表达式匹配 P 标签?

php - 如何将此字符串与正则表达式匹配

python - 从列表中删除正则表达式元素