【问题标题】:return multiple matches using re.match or re.search使用 re.match 或 re.search 返回多个匹配项
【发布时间】:2018-10-02 06:52:39
【问题描述】:

我正在将一些代码转换为micropython,但我遇到了一个特定的正则表达式。

在python中我的代码是

import re

line = "0-1:24.2.1(180108205500W)(00001.290*m3)"
between_brackets = '\(.*?\)' 

brackettext  = re.findall(between_brackets, line) 
gas_date_str = read_date_time(brackettext[0])
gas_val      = read_gas(brackettext[1])

# gas_date_str and gas_val take the string between brackets 
# and return a value that can later be used

micropython 只实现a limited set of re functions

如何仅使用有限的功能来实现相同的功能?

【问题讨论】:

    标签: python python-3.x micropython


    【解决方案1】:

    您可以按照以下方式进行操作。在使用字符串时重复使用re.search。这里的实现使用了一个生成器函数:

    import re
    
    def findall(pattern, string):
        while True:
            match = re.search(pattern, string)
            if not match:
                break
            yield match.group(0)
            string = string[match.end():]
    
    >>> list(findall(r'\(.*?\)', "0-1:24.2.1(180108205500W)(00001.290*m3)"))
    ['(180108205500W)', '(00001.290*m3)']
    

    【讨论】:

    • 我喜欢代码的紧凑性和yield的使用。
    • 值得一提的是,虽然 match.end 在核心 MicroPython 库中,但它的实现因端口而异。因此,例如在 PyCom 板上……没有 .end()。 (无论如何从今天开始)
    【解决方案2】:

    您可以使用re.search() 编写一个返回所有匹配项列表的方法:

    import re  
    
    def find_all(regex, text):
        match_list = []
        while True:
            match  = re.search(regex, text)
            if match:
                match_list.append(match.group(0))
                text = text[match.end():]
            else:
                return match_list
    

    另外,请注意您的 between_brackets 正则表达式不会处理嵌套括号:

    re.findall('\(.*?\)', "(ac(ssc)xxz)")
    >>> ['(ac(ssc)']
    

    【讨论】:

    • 谢谢。也许更优雅的做法是将 match 语句作为 while 循环的条件,并将 return 语句放在循环之外
    • 啊,没关系。您不能将赋值作为 while 语句的一部分进行
    • “另外,请注意,您的 between_brackets 正则表达式不会处理嵌套括号:” - 感谢您指出这一点。我知道我试图解析的数据不会出现这些情况。如果确实重要,我应该如何处理这些情况?
    • 正则表达式是处理递归文本的错误工具。如果需要,您可以实施accepted answer here 中描述的解决方案。
    • 感谢您的链接。正则表达式是否适合我的情况,还是您也会在这里推荐一个子例程?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 2015-12-08
    • 1970-01-01
    • 2013-11-25
    相关资源
    最近更新 更多