我正在从一个字符串列表中提取代码,使用来自标题电子邮件。看起来像:
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']
简单的模式
M?[-\d]+
应该适合您。下面是一个演示:在您的模式中,character类
[p/n:]\s+
将匹配列出的字符之一,后跟1+空格字符。在本例中,匹配正斜杠或冒号后跟空格的数据。你知道吗下一部分
(?:\w+(?:\s+|$))
将匹配1+个单词字符,后跟字符串结尾或1+个空格字符,而不考虑中间的空格字符或连字符。你知道吗一个选项是将PN与可选的
:
和/
匹配,而不是使用字符类[p/n:]
,并将您的值包含在捕获组中:Regex demo| Python demo
例如:
结果
相关问题 更多 >
编程相关推荐