使用正则表达式删除字符串末尾的不可预测的日期格式

时间:2015-02-25 18:51:23

标签: python regex

我以下列方式获取字符串,最后以随机模式显示日期。但它只包含下划线,斜线,数字或连字符。

TRAVEL_DELAY_01072015
TRAVEL_DELAY_01_07_2015
TRAVEL_DELAY_2015/01/04
TRAVEL_DELAY_2015-01-04

我需要从上面的字符串中取出TRAVEL_DELAY。我正在使用正则表达式,但不工作:

m = re.match("^(.*)[_0-9\/.]+", abovestring)

2 个答案:

答案 0 :(得分:3)

如果这就是你要做的全部,为什么不删除 TRAVEL_DELAY而不是匹配其余的?你可以实现这样的东西:

m = re.sub('TRAVEL_DELAY', '', m)

如果您的问题比这更复杂,请告诉我。

编辑:根据您的评论,您想删除所有字母字符,因此您正在寻找此正则表达式。

m = re.sub('[_A-Z_a-z_]','', m)

答案 1 :(得分:3)

如果您只想分割日期:

s="""TRAVEL_DELAY_01072015
TRAVEL_DELAY_01_07_2015
TRAVEL_DELAY_2015/01/04
TRAVEL_DELAY_2015-01-04"""

for line in s.splitlines():
    date = line.split("_",2)[-1]

01072015
01_07_2015
2015/01/04
2015-01-04

str.replace,不需要正则表达式:

for line in s.splitlines():
    date = line.replace("TRAVEL_DELAY_","")
    print(date)

 01072015
 01_07_2015
 2015/01/04
 2015-01-04

如果您实际上正在尝试解析日期,可以使用dateutil并修复字符串:

from dateutil import parser
for line in s.splitlines():
    date = line.replace("TRAVEL_DELAY_","")
    if any(ch in date for ch in ("/","-","_")):
        print(parser.parse(date.replace("_","-")))
    else:
        date = "{}-{}-{}".format(date[:2],date[2:4],date[4:])
        print(parser.parse(date))


2015-01-07 00:00:00
2015-01-07 00:00:00
2015-01-04 00:00:00
2015-01-04 00:00:00

如果数字仅在日期中,并且您希望字符串不是日期:

 s="""TRAVEL_DELAY_01072015
TRAVEL_DELAY_01_07_2015
TRAVEL_DELAY_2015/01/04
Travel_Delay_Data_2015/01/04
TRAVEL_DELAY_2015-01-04"""

for line in s.splitlines():
    ind = next(ind for ind, ele in enumerate(line) if ele.isdigit())
    s = line[:ind-1]
    print(s)

TRAVEL_DELAY
TRAVEL_DELAY
TRAVEL_DELAY
Travel_Delay_Data
TRAVEL_DELAY