我在写函数的时候遇到了问题。目标是输入一个字符串:即'from 16:00-17:00 we will be bowling and from 18:00-19:00 there is dinner'它应该返回一个带有[16:00-17:00, 18:00-19:00]的列表我想用regex来做这个,用re.findall来搜索时间模式,但是我不能让它工作。有人有什么建议吗?
'from 16:00-17:00 we will be bowling and from 18:00-19:00 there is dinner'
[16:00-17:00, 18:00-19:00]
regex
re.findall
mfuanj7w1#
可以使用以下模式:\d{2}\:\d{2}\-\d{2}\:\d{2}
\d{2}\:\d{2}\-\d{2}\:\d{2}
\d{2}
\:
\-
import restrs = ['from 16:00-17:00 we will be bowling and from 18:00-19:00 there is dinner', 'from 12:00-14:00 we will be bowling and from 15:00-17:00 there is dinner', 'from 10:00-16:30 we will be bowling and from 18:30-18:45 there is dinner']pat = '\d{2}\:\d{2}\-\d{2}\:\d{2}'for s in strs: times = re.findall(pat, s) print(times)
import re
strs = ['from 16:00-17:00 we will be bowling and from 18:00-19:00 there is dinner',
'from 12:00-14:00 we will be bowling and from 15:00-17:00 there is dinner',
'from 10:00-16:30 we will be bowling and from 18:30-18:45 there is dinner']
pat = '\d{2}\:\d{2}\-\d{2}\:\d{2}'
for s in strs:
times = re.findall(pat, s)
print(times)
字符串
输出:
['16:00-17:00', '18:00-19:00']['12:00-14:00', '15:00-17:00']['10:00-16:30', '18:30-18:45']
['16:00-17:00', '18:00-19:00']
['12:00-14:00', '15:00-17:00']
['10:00-16:30', '18:30-18:45']
型Regex Example
1条答案
按热度按时间mfuanj7w1#
可以使用以下模式:
\d{2}\:\d{2}\-\d{2}\:\d{2}
\d{2}
匹配出现2次的数字(等于[0-9])\:
匹配字符:literally(区分大小写)\-
匹配字符-按字面意思(区分大小写)产品代码:
字符串
输出:
型
Regex Example