Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
日期正则表达式中的查找(python)_Python_Regex_Date - Fatal编程技术网

日期正则表达式中的查找(python)

日期正则表达式中的查找(python),python,regex,date,Python,Regex,Date,我在理解Python背后的外观时遇到了一些困难。更具体地说,我有一段文本,日期采用(mm/dd/yyyy)(mm-dd-yyyy)格式,年份采用(yyyy)格式: Jan-01-2001 Jan 01 2001 2003 2007 The year was 2009 when x decided to work for Google 仅提取具有yyyy的行的最佳匹配方式是什么。我应该能够提取2003、2007和2009,但不能提取任何其他日期,如2001年1月1日和2001年1月1日。我尝试了

我在理解Python背后的外观时遇到了一些困难。更具体地说,我有一段文本,日期采用
(mm/dd/yyyy)
(mm-dd-yyyy)
格式,年份采用
(yyyy)
格式:

Jan-01-2001
Jan 01 2001
2003 2007
The year was 2009 when x decided to work for Google
仅提取具有
yyyy
的行的最佳匹配方式是什么。我应该能够提取
2003
2007
2009
,但不能提取任何其他日期,如
2001年1月1日
2001年1月1日
。我尝试了lookbehind操作符,我能得到的最好结果是
((?。但这只选择了
2003
而不是
2007
2009
。我还尝试使用组来定义日期模式,并将其与lookback结合使用,但这不起作用。在正则表达式(Python)中这样做的正确有效方法是什么 这只适用于您提供的示例字符串(并且年份前面没有2位数字后跟空格或连字符)。假设所有日期都使用2位数字来定义一个月中的一天,这将适用于您(因为python中的lookbehinds(以及大多数正则表达式引擎)无法量化)


代码

输出
解释
  • \b
    将位置断言为单词边界
  • (?反向查找确保前面的内容与下面的内容不匹配
    
    • \b
      将位置断言为单词边界
    • \d{2}
      正好匹配两位数字
    • [-]
      匹配空格
      或连字符
      -
      字符
  • \d{4}
    精确匹配4位数字
  • \b
    将位置断言为单词边界

最简单的方法可能是识别日期,然后只捕获与日期不匹配(或部分匹配)的内容:
\b\d{1,2}[-]\d{4}|(\d{4}\b)
-抓取捕获组1不需要。我正在寻找一个带有查找功能的正则表达式,该正则表达式允许我只捕获那些只有年份的字符串。您提供的内容将捕获所有年份(即,即使它们是(mm dd yyyy)或(mm/dd/yyyyy)格式的一部分。您的正则表达式是
\d{4}
。它将选择任意四位。@N00bsie我已经重新编辑了我的答案,请检查一下。现在可能会对你有帮助吗谢谢你的解释@ctwheels。这很有帮助。你是对的。显然,如果我有一句话,比如说,
今年是2009年,我决定在2004年1月1日为谷歌工作,这是行不通的。我需要它来工作还有。我将尝试修改您的正则表达式,使其包含
\w{3}
@N00bsie您必须为每种可能性添加一个新的负面查找,例如:
\b(?。非常感谢您的回复@ctwheels。现在就有意义了。
\b(?<!\b\d{2}[ -])\d{4}\b
Jan-01-2001
Jan 01 2001
2003 2007
The year was 2009 when x decided to work for Google
2003
2007
2009
I hope this may help you:

import re
string = """Jan-01-2001
Jan 01 2001
2003 2007 
The year was 2009 when x decided to work for Google"""
for year in string.split('\n'):
    search_date = re.search(r'^(?!\w{3}(?:\s+|-)\d{2}(?:\s+|-)\d{4}).+',year)
    if search_date:
      print(re.findall(r'\d{4}',search_date.group()))