我有一个包含日期时间的字符串,我试图根据日期时间的出现拆分字符串,
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 个空格后跟类似日期的模式进行分割,因此,你可以使用
re.split(r'\s+(?=\d{2}(?:\d{2})?-\d{1,2}-\d{1,2}\b)', s)
参见 regex demo
详情
\s+
- 1+ 个空白字符(?=\d{2}(?:\d{2})?-\d{1,2}-\d{1,2}\b)
- 一个 < em>positive lookahead 确保在当前位置的左侧有\d{2}(?:\d{2})?
- 2 或 4 位数字-
- 连字符\d{1,2}
- 1 或 2 位数字-\d{1,2}
- 同样是连字符和 1 或 2 位数字\b
- 单词边界(如果不需要,将其删除,或替换为(?!\d)
以防您将日期粘在字母上或其他文字)
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*
将允许零长度匹配)。对于旧版本,您需要使用解决方案 as @blhsing suggests或安装 PyPi regex module并使用 r"(?V1)\s*(?=\d{2}(?:\d{2})?-\d{1,2}-\d{1,2}\b )"
与 regex.split
。
关于python - 正则表达式模式以匹配 python 中的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51395590/