Skip to main content
 首页 » 编程设计

python之根据python中的模式拆分和分组字符串

2024年10月25日24sxdcgaq8080

问题: 我有以下示例字符串:

ex1 = "00:03:34 hello!! this is example number 1 00:04:00" 
ex2 = "00:07:08 Hi I am example number 2" 

我希望它像下面这样分组(输出):

ex1 out : ("00:03:34", "hello!! this is example number 1", "00:04:00") 
ex2 out : ("00:07:08", "Hi I am example number 2", None) 

尝试:

我试过重新拆分:

time_pat = r"(\d{2}:\d{2}:\d{2})" 
re.split(time_pat, ex1) 
re.split(time_pat, ex2) 

它给了我以下输出:

ex1 out : ['', '00:03:34', ' hello!! this is example number 1 ', '00:04:00', ''] 
ex2 out : ['', '00:07:08', ' Hi I am example number 2'] 

我将使用过滤器去除空白,然后输出看起来像

ex1 out : ['00:03:34', ' hello!! this is example number 1 ', '00:04:00'] 
ex2 out : ['00:07:08', ' Hi I am example number 2'] 

这里的问题是 ex2 输出的长度为 2 而不是 3,第三个元素为 None。我知道如果长度为 2,我可以附加 None 但我不想这样做,我相信正则表达式可以做到这一点。

我试过以下正则表达式:

re1 : r"(\d{2}:\d{2}:\d{2})(.*)(\d{2}:\d{2}:\d{2})" 

很明显,它会解析 ex1 但不会解析 ex2

re2 : r"(\d{2}:\d{2}:\d{2})(.*)(\d{2}:\d{2}:\d{2})?" 

这将解析两者,但第三个字符串始终为 None,因为正则表达式中的“.*”使用结束时间模式。

我已经尝试过先行断言,但我只是试错了,因此没有给出任何结果。谁能帮我得到这里的正则表达式?

请您参考如下方法:

你可以像你建议的那样使用前瞻,或者你可以只使用非贪婪捕获,一个可选的组并指定你想要匹配直到行尾 ($):

import re 
 
ex1 = "00:03:34 hello!! this is example number 1 00:04:00" 
ex2 = "00:07:08 Hi I am example number 2" 
 
for ex in [ex1, ex2]: 
    mat = re.match(r'(\d{2}:\d{2}:\d{2})\s(.*?)\s*(\d{2}:\d{2}:\d{2})?$', ex) 
    if mat: print mat.groups() 

输出:

('00:03:34', 'hello!! this is example number 1', '00:04:00') 
('00:07:08', 'Hi I am example number 2', None) 

注意:这与您所拥有的非常接近——我只是对中间组使用了非贪婪捕获((.*?) 中的 ?)并在末尾添加一个 $ 以告诉它匹配整行。如果没有非贪婪捕获,最后的可选时间戳将被中间组吃掉,并且没有指定要匹配到行尾,解析器甚至不会尝试匹配非贪婪中间组和可选的时间戳,因为它不需要。