【问题标题】:Extracting Specific Regex result from string从字符串中提取特定的正则表达式结果
【发布时间】: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 零件编号只能包含数字和字母。

标签: python regex python-re


【解决方案1】:

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

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

说明

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

regex demo | Python demo

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

【讨论】:

    【解决方案2】:

    以下是提取匹配文本的方法。如 cmets 中所述,这并不能解决正则表达式的问题,但会按照您的要求提取匹配值。问题是整行与您编写正则表达式的方式匹配。

    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:
        m = re.search(r'^(?=.*\d).{5,}$', item)
        if m is not None:
            print(m.group(0))
    

    【讨论】:

      猜你喜欢
      • 2021-05-24
      • 2019-03-13
      • 2021-11-09
      • 2014-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多