【发布时间】:2021-01-16 20:47:55
【问题描述】:
我正在尝试从字符串中提取零件编号。我将遍历项目,如果项目长度超过 4 个字符,并且包含至少 1 个数字,则需要提取该项目。它不必包含字母,但可以。
例如:
Line1: 'There is some random information here'
Line2: 'This includes item p23344dd5 as well as other info'
Line3: 'K3455 $100.00'
Line4: 'Last part number here 5551234'
我需要提取 3 个项目编号 p23344dd5、K3455 和 5551234。
我正在使用此代码,但它只会在匹配时返回,这不是我需要的。我需要返回匹配的文本。
import re
items = ['There is some random information here',
'This includes item p23344dd5 as well as other info',
'K3455 $100.00',
'Line4: ''Last part number here 5551234']
for item in items:
x = re.search(r'^(?=.*\d).{5,}$', item)
print(x)
【问题讨论】:
-
$100.00长度超过 4 个字符,并且至少包含一个数字。什么构成单词边界? -
没错,而且看起来它也在返回,所以我需要编辑我的正则表达式以排除它。
-
如果应该排除,为什么?它符合您的要求。
-
我认为@ggorlen 提出的这个问题很好。什么定义了零件号。这里还有其他规格或模式可供选择吗?还是零件号只允许使用数字和字母字符?
-
@JvdV 零件编号只能包含数字和字母。