【问题标题】:How to write regular expression to extract years如何编写正则表达式来提取年份
【发布时间】:2023-03-28 17:05:01
【问题描述】:

我们如何编写正则表达式来提取文本中的年份,年份可能有以下形式

Case 1:
1970 - 1980 --> 1970, 1980
January 1920 - Feb 1930 --> 1920, 1930
May 1920 to September 1930 --> 1920, 1930
Case 2:
July 1945 --> 1945

Case 1 编写正则表达式很容易,但我如何处理Case 2 以及它

\d{4} \s? (?: [^a-zA-Z0-9] | to) \s? \w+? \d{4}

【问题讨论】:

  • 你能用\b\d{4}\b吗?
  • Writing regular expression for Case 1 is easy 我会支持一下。您的正则表达式不匹配任何内容。

标签: regex python-3.x information-extraction


【解决方案1】:

根据您的要求,只需匹配所有 4 位数字

import re
s = '''1970 - 1980
January 1920 - Feb 1930
May 1920 to September 1930
July 1945'''

p = re.compile(r'\b\d{4}\b')

s = s.splitlines()
for x in s:
    result = p.findall(x) 
    print(result)

输出

['1970', '1980']
['1920', '1930']
['1920', '1930']
['1945']

【讨论】:

    【解决方案2】:

    正则表达式.*?([0-9]{4})(?:.*?([0-9]{4}))?.*?(\d{4})(?:.*?(\d{4}))?

    详情:

    • ()抓拍组
    • (?:)非捕获组
    • {n} 完全匹配 n
    • .*? 匹配零次到无限次之间的任何字符(惰性)

    Python 代码

    def Years(text):
            return re.findall(r'.*?([0-9]{4})(?:.*?([0-9]{4}))?', text)
    
    print(Years('January 1920 - Feb 1930'))
    

    输出:

    [('1920', '1930')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多