用正则表达式(不规则正则表达式键)提取代码

2024-10-03 00:19:44 发布

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

我正在从一个字符串列表中提取代码,使用来自标题电子邮件。看起来像:

text_list = ['Industry / Gemany / PN M564839', 'Industry / France / PN: 575-439', 'Telecom / Gemany / P/N 26-59-29', 'Mobile / France / P/N: 88864839']

到目前为止,我尝试的是:

def get_p_number(text):
    rx = re.compile(r'[p/n:]\s+((?:\w+(?:\s+|$)){1})',
                    re.I)
    res = []
    m = rx.findall(text)
    if len(m) > 0:
        m = [p_number.replace(' ', '').upper() for p_number in m]
        m = remove_duplicates(m)
        res.append(m)
    else:
        res.append('no P Number found')
    return res

我的问题是,我无法提取['PN', 'P/N', 'PN:', 'P/N:']前面的单词旁边的代码,特别是如果后面的代码以字母(即“m”)开头,或者中间有斜杠(即26-59-29)。你知道吗

我想要的结果是:

res = ['M564839','575-439','26-59-29','888489']

Tags: 字符串代码textre标题number列表res
2条回答

简单的模式M?[-\d]+应该适合您。下面是一个演示:

import re

text_list = ['Industry / Gemany / PN M564839', 'Industry / France / PN: 575-439', 'Telecom / Gemany / P/N 26-59-29', 'Mobile / France / P/N: 88864839']

res = []
for elem in text_list:
    for code in re.findall(r'M?[-\d]+', elem):
        res.append(code)

print(res)

Output:

['M564839', '575-439', '26-59-29', '88864839']

在您的模式中,character类[p/n:]\s+将匹配列出的字符之一,后跟1+空格字符。在本例中,匹配正斜杠或冒号后跟空格的数据。你知道吗

下一部分(?:\w+(?:\s+|$))将匹配1+个单词字符,后跟字符串结尾或1+个空格字符,而不考虑中间的空格字符或连字符。你知道吗

一个选项是将PN与可选的:/匹配,而不是使用字符类[p/n:],并将您的值包含在捕获组中:

/ P/?N:? ([\w-]+)

Regex demo| Python demo

例如:

import re
text_list = ['Industry / Gemany / PN M564839', 'Industry / France / PN: 575-439', 'Telecom / Gemany / P/N 26-59-29', 'Mobile / France / P/N: 88864839']
regex = r"/ P/?N:? ([\w-]+)"
res = []
for text in text_list: 
    matches = re.search(regex, text)
    if matches:
        res.append(matches.group(1))

print(res)

结果

['M564839', '575-439', '26-59-29', '88864839']

相关问题 更多 >