python - 正则表达式模式以匹配 python 中的日期时间

标签 python regex python-3.x pandas datetime

我有一个包含日期时间的字符串,我试图根据日期时间的出现拆分字符串,

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) 以防您将日期粘在字母上或其他文字)

Python demo :

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/

相关文章:

python - 将 Django 博客项目集成到 HTML 网站中

python - 访问我的网站页面后无法登录管理页面

R gregexpr 上的正则表达式匹配

python - 将类似列表的长字符串转换为新列表

python - 将列重新格式化为仅前 5 个字符

python - 是什么阻止用户插入表中?

python - 使用 QAbstractTableModel 在 pyqts QTableView 中插入和删除行

java - 使用 java.lang.String.matches() 查找匹配项

python-3.x - 修复将空列表分配给值 "DNA_Sequence"时出现的错误

python - open cv2 python中Tensor flow 2.0对象的使用方法是什么,为什么这么迂回?