簡體   English   中英

正則表達式模式以匹配python中的日期時間

[英]regex pattern to match datetime in python

我有一個包含日期時間的字符串,我正在嘗試根據日期時間出現次數拆分該字符串,

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)進行拆分,因此,您可以使用

re.split(r'\s+(?=\d{2}(?:\d{2})?-\d{1,2}-\d{1,2}\b)', s)

正則表達式演示

細節

  • \\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) ,以防可能將日期粘貼到字母或其他文本上)

Python演示

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建議的解決方案或安裝PyPi regex模塊並使用r"(?V1)\\s*(?=\\d{2}(?:\\d{2})?-\\d{1,2}-\\d{1,2}\\b)"regex.split

re.split用於具有特定定界符模式的情況。 使用re.findall模式的re.findall代替:

import re
data="2018-03-14 06:08:18, he went on \n2018-03-15 06:08:18, lets play"
d = r'\d{4}-\d?\d-\d?\d (?:2[0-3]|[01]?[0-9]):[0-5]?[0-9]:[0-5]?[0-9]'
print(re.findall(r'{0}.*?(?=\s*{0}|$)'.format(d), data, re.DOTALL))

輸出:

['2018-03-14 06:08:18, he went on', '2018-03-15 06:08:18, lets play']

使用組的類似但替代的解決方案:

import re

data="2018-03-14 06:08:18, he went on 2018-03-15 06:08:18, lets play"

print(re.findall(r'(.*?\D{2,})', data))

這使:

['2018-03-14 06:08:18, he went on ', '2018-03-15 06:08:18, lets play']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM