Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return multiple matches using re.match or re.search

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?

like image 632
Marc Wagner Avatar asked Jan 18 '26 03:01

Marc Wagner


1 Answers

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)']
like image 55
user2390182 Avatar answered Jan 20 '26 17:01

user2390182