使用正则表达式开始和停止

2024-10-04 07:32:26 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的程序中,我使用正则表达式直到单词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   

Tags: textin程序reforsearchifmatch
2条回答

最简单的就是使用

my_re = re.compile("your regex")
my_re.search(some_string)
my_re.search(some_other_string)

这样就避免了两次定义正则表达式。你知道吗

根据文档的内容,您可以按“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”)。你知道吗

以下是代码的替换:

import re
searcher = re.compile(r'\b(?:2[0-3]|[01][0-9])[0-5][0-9]\b').search
with open(filename) as text:
        for line in text:
            m = searcher(line)
            if m:
                do_something_1(line, m)
            if line.startswith("BREAK"): # equivalent to your code; is that what you really mean??
                break
        for line in text:
            m = searcher(line)
            if m:
                do_something_2(line, m)
            if line.startswith("STOP"): # equivalent to your code; is that what you really mean??
                break   

相关问题 更多 >