【问题标题】:Extracting codes with regex (irregular regex keys)使用正则表达式提取代码(不规则的正则表达式键)
【发布时间】:2019-11-11 20:12:46
【问题描述】:

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

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']

【问题讨论】:

    标签: python regex python-3.x pandas dataframe


    【解决方案1】:

    在您的模式中,字符类 [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']
    

    【讨论】:

      【解决方案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)
      

      输出:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-08-08
        • 2012-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多