首页 > 解决方案 > 从字符串中提取特定的正则表达式结果

问题描述

我正在尝试从字符串中提取零件号。我将遍历项目,如果项目长度超过 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)

标签: pythonregexre

解决方案


要匹配问题中的值,您可以从空白边界声明至少 5 个单词字符,然后匹配至少一个数字。

(?<!\S)(?=\w{5})[^\W\d]*\d\w*(?!\S)

解释

  • (?<!\S)左边的空白边界
  • (?=\w{5})断言 5 个单词字符
  • [^\W\d]*匹配没有数字的可选单词字符
  • \d匹配 1 位数字
  • \w*匹配可选的单词字符
  • (?!\S)在右侧断言空白边界

正则表达式演示| Python 演示

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'(?<!\S)(?=\w{5})\w*\d\w*(?!\S)', item)
    if x:
        print(x.group())

p23344dd5
K3455
5551234

推荐阅读