通过正则表达式提取日期

sam*_*sam -6 python regex

我有一个字符串.

s = "20160204094836A"
Run Code Online (Sandbox Code Playgroud)

我想使用正则表达式获取如下日期.

date = "20160204"
start_date = date(int("2016"), int("02"), int("04"))
Run Code Online (Sandbox Code Playgroud)

所以,简而言之,我需要获得年,日,月.通过正则表达式可以实现这样的事吗?

Kea*_*nge 5

没有正则表达式:

s = "20160204094836A"

year = s[:4]
day = s[4:6]
month = s[6:8]

print(year, day, month)
Run Code Online (Sandbox Code Playgroud)

使用正则表达式:

import re

s = "20160204094836A"
result = re.search(r"^(\d{4})(\d{2})(\d{2})", s)
year = int(result.group(1))
day = int(result.group(2))
month = int(result.group(3))

print(year, day, month)
Run Code Online (Sandbox Code Playgroud)