return multiple matches using re.match or re.search

微笑、不失礼 提交于 2020-01-02 13:26:13

问题


I am converting some code to micropython and I got stuck on a particular regular expression.

In python my code is

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 only implements a limited set of re functions

how do I achieve the same with only the limited functions available?


回答1:


You could do something along the following lines. Repeatedly use re.search while consuming the string. The implementation here uses a generator function:

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)']



回答2:


You can write a method using re.search() that returns a list of all matches:

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

Also, note that your between_brackets regex will not take care of nested brackets:

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


来源:https://stackoverflow.com/questions/52603287/return-multiple-matches-using-re-match-or-re-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!