【问题标题】:Python Regex extractall for (YYYY) only but not MMM YYYYPython Regex extractall for (YYYY) only 但不是 MMM YYYY
【发布时间】:2018-10-10 22:46:10
【问题描述】:

我有一个包含文本的列(文本行)的数据框 df

df['textline'].iloc[0] = 'This is a test with 2018\n'
df['textline'].iloc[1] = 'This is a test with Jan 2018\n'
df['textline'].iloc[2] = 'This is a test with Feb 2018\n'

我想使用 Regex extractall 来遍历整个 df['textline'] 但它只会在没有前面的月份名称时提取年份。例如,在上面的示例中,它将从第一行中提取 2018 年,但不会从第二行或第三行中提取 2018 年,因为它有 Jan 或 Feb(或其他月份)。

df['textline'].str.extractall(r'<<Regex code>>')

【问题讨论】:

  • 这就是我要找的:正则表达式模式来做到这一点。
  • 另外,请扩展正则表达式代码以不提取内容为 2018 年 1 月、2018 年 1 月等内容的行。我只想要纯 2018(无月份)的行
  • 例如这是尝试: df['textline'].str.extractall(r' ^(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* (\d{4})\D')

标签: python regex


【解决方案1】:

我想出了答案的第一部分:

df['textline'].str.extractall(r'(?<!Jan|Feb) ([1-2][0-9]{3})')

第二部分是如何为整个单词 January , February 使用同一行,以便它适用于 Feb 2018 和 February 2018

【讨论】:

    【解决方案2】:

    你可以试试这个:

    (?<=(\s))\d{4}(?=\D)
    

    匹配:

    这是 2018 的测试\n

    这是 2018 年 1 月的测试\n

    这是 2018 年 2 月的测试\n

    【讨论】:

      猜你喜欢
      • 2023-01-20
      • 1970-01-01
      • 1970-01-01
      • 2012-09-12
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多