正则表达式模式以匹配python中的日期时间 [英] regex pattern to match datetime in python
问题描述
我有一个包含日期时间的字符串,我正在尝试根据日期时间出现次数来拆分字符串,
I have a string contains datetimes, I am trying to split the string based on the datetime occurances,
data="2018-03-14 06:08:18, he went on \n2018-03-15 06:08:18, lets play"
我在做什么
out=re.split('^(2[0-3]|[01]?[0-9]):([0-5]?[0-9]):([0-5]?[0-9])$',data)
我会得到什么
["2018-03-14 06:08:18, he went on 2018-03-15 06:08:18, lets play"]
我想要什么:
["2018-03-14 06:08:18, he went on","2018-03-15 06:08:18, lets play"]
推荐答案
您希望使用至少1个空格和后跟日期(如pattern)进行拆分,因此,您可以使用
You want to split with at least 1 whitespace followed with a date like pattern, thus, you may use
re.split(r'\s+(?=\d{2}(?:\d{2})?-\d{1,2}-\d{1,2}\b)', s)
请参见 regex演示
详细信息
-
\s+
-1个以上空格字符 -
(?=\d{2}(?:\d{2})?-\d{1,2}-\d{1,2}\b)
-一个正向超前,可确保在当前位置的左侧紧随其后-
\d{2}(?:\d{2})?
-2位或4位数字 -
-
-连字符 -
\d{1,2}
-1或2位数字 -
-\d{1,2}
-再加上一个连字符和1或2位数字 -
\b
-单词边界(如有必要,请将其删除,或将其替换为(?!\d)
,以防您将日期粘贴到字母或其他文本上)
\s+
- 1+ whitespace chars(?=\d{2}(?:\d{2})?-\d{1,2}-\d{1,2}\b)
- a positive lookahead that makes sure, that immediately to the left of the current location, there are\d{2}(?:\d{2})?
- 2 or 4 digits-
- a hyphen\d{1,2}
- 1 or 2 digits-\d{1,2}
- again a hyphen and 1 or 2 digits\b
- a word boundary (if not necessary, remove it, or replace with(?!\d)
in case you may have dates glued to letters or other text)
import re rex = r"\s+(?=\d{2}(?:\d{2})?-\d{1,2}-\d{1,2}\b)" s = "2018-03-14 06:08:18, he went on 2018-03-15 06:08:18, lets play" print(re.split(rex, s)) # => ['2018-03-14 06:08:18, he went on', '2018-03-15 06:08:18, lets play']
注意如果日期前不能有空格,则在Python 3.7及更高版本中,您可以使用
r"\s*(?=\d{2}(?:\d{2})?-\d{1,2}-\d{1,2}\b)"
(请注意,将*
量词与\s*
配合使用,将允许零长度匹配).对于较旧的版本,您需要按照@blhsing的建议使用解决方案或安装与regex.split
一起使用.NOTE If there can be no whitespace before the date, in Python 3.7 and newer you may use
r"\s*(?=\d{2}(?:\d{2})?-\d{1,2}-\d{1,2}\b)"
(note the*
quantifier with\s*
that will allow zero-length matches). For older versions, you will need to use a solution as @blhsing suggests or install PyPi regex module and user"(?V1)\s*(?=\d{2}(?:\d{2})?-\d{1,2}-\d{1,2}\b)"
withregex.split
.这篇关于正则表达式模式以匹配python中的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-