【发布时间】:2015-03-28 03:28:16
【问题描述】:
问题: 我有以下示例字符串:
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,因为正则表达式中的 ".*" 消耗了结束时间模式。
我尝试过前瞻断言,但我尝试错误,因此没有结果。谁能帮我在这里获取正则表达式?
【问题讨论】:
-
如果输入是
Hi I am example number 2,你的预期输出是什么?
标签: python regex python-2.7