Search code examples
python-3.xregexpython-re

Regex find digits at the end of multiple strings


Below is my string, its coming from a stdout.

I am looking for a way to find all the decimal numbers for a sensor. I want to provide my regex pattern "TP1" and would like my return to look like this:

[156.2 , 30]

I am using re.findall()

TP1   BCArc                                    156.2
TP2   Max: of output here                      0.01
TP3   some:other example 1 here                30.70
TP1   BCArc                                    30
TP2   Max: of output here                      2.22

I can find the end of a string but not with the input: see here: https://regex101.com/r/IyqtsL/1

Here is the code Im trying

\d+\.\d+?$

Solution

  • Enable Multiline mode through flags: on regex101.com, that option is available on the right side of the pattern input field (where by default you can see /g. When using the regex in Python, you can pass flags as the third parameter to re.findall():

    import re
    
    sensor = "TP1"
    text = """
    TP1   BCArc                                    156.2
    TP2   Max: of output here                      0.01
    TP3   some:other example 1 here                30.70
    TP1   BCArc                                    30
    TP2   Max: of output here                      2.22
    """
    re.findall(fr'^{sensor}\s+\w+\s+([\d\.]+)$', text, re.MULTILINE)
    # returns ['156.2', '30]
    

    All flags are described in the documentation.