在我的程序中,我使用正则表达式直到单词break,然后我再次使用它直到单词stop。程序的第一部分将比赛从军事时间转换为常规时间。第二部分将军事时间除以用户输入的数字。我的代码可以工作,但我使用正则表达式两次。怎样才能改变我的程序,使我只使用正则表达式一次。你知道吗
with open(filename) as text:
for line in text:
pattern = re.search(r'((((2)([0-3]))|(([0-1])([0-9])))([0-5])([0-9]))', line)
if pattern:
if re.match("BREAK", line):
break
for line in text:
m= re.search(r'((((2)([0-3]))|(([0-1])([0-9])))([0-5])([0-9]))', line)
if m:
if re.match("STOP", line):
break
最简单的就是使用
这样就避免了两次定义正则表达式。你知道吗
根据文档的内容,您可以按“BREAK”拆分或匹配多个,如果看不到示例或更多定义,则很难知道。你知道吗
首先,您的正则表达式
r'((((2)([0-3]))|(([0-1])([0-9])))([0-5])([0-9]))'
中有大量的括号。你知道吗可能您没有使用这样创建的捕获组。您似乎想要匹配HHMM,其中HH是00到23,MM是00到59。你知道吗
r'(2[0-3]|[01][0-9])[0-5][0-9]
将做同样的工作。您可以通过执行r'(?:2[0-3]|[01][0-9])[0-5][0-9]'
来避免剩下的一个捕获组。你知道吗您可能希望通过(例如)在模式的每一端具有
\b
来避免虚假匹配(例如,“blah 23456789”中的“2345”)。你知道吗以下是代码的替换:
相关问题 更多 >
编程相关推荐