[英]Python Cannot Parse Date with Regex
I have a program in which the user can enter a string and have the date in the string. 我有一个程序,用户可以在其中输入字符串,并在字符串中包含日期。 I am using RegEx to match
\\d+\\/\\d+\\/\\d+
to extract the date from the string but for some reason in my test case, only the last entry is able to work 我正在使用RegEx来匹配
\\d+\\/\\d+\\/\\d+
从字符串中提取日期,但是由于某种原因,在我的测试案例中,只有最后一个条目才可以工作
import datetime
import re
dateList = []
dates = ["Foo (8/15/15) Bar", "(8/15/15)", "8/15/15"]
reg = re.compile('(\d+\/\d+\/\d+)')
for date in dates:
matching = reg.match(date)
if matching is not None:
print date, matching.group(1)
else:
print date, "is not valid date"
returns 回报
Foo (8/15/15) Bar is not valid date
(8/15/15) is not valid date
8/15/15 8/15/15
Is there something wrong with my RegEx? RegEx出问题了吗? I tested it with RegEx101.com and it seemed to work fine
我在RegEx101.com上进行了测试,它似乎可以正常工作
if you are looking for a partial match of the regex, use search: 如果您要查找正则表达式的部分匹配项,请使用搜索:
import datetime
import re
dateList = []
dates = ["Foo (8/15/15) Bar", "(8/15/15)", "8/15/15"]
reg = re.compile('([0-9]+/[0-9]+/[0-9]+)')
for date in dates:
matching = reg.search(date) # <- .search instead of .match
if matching is not None:
print( date, matching.group(1) )
else:
print( date, "is not valid date" )
You are looking for search()
, not match()
. 您正在寻找
search()
,而不是match()
。
date_re = re.compile('([0-9]{2})/([0-9]{2})/([0-9]{2})')
e = date_re.match('foo 01/02/13')
# e is None
e = date_re.search('foo 01/02/13')
# e.groups() == ('01', '02', '13')
Do not use \\d
where you expect the ASCII 0-9 digits because there are many strange things matched by the Unicode version of \\d
. 不要在期望使用ASCII 0-9数字的地方使用
\\d
,因为\\d
的Unicode版本会匹配很多奇怪的东西 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.