Search code examples
pythonregexmulti-selectmultiline

How to Match mutilple line string using Python Regex?


I have a below 2 lines :

/begin MEASUREMENT ANYNAME1 "Unterstützungskraft Softwaremodul "

SWORD ANYNAME2 1 100 -Randomdigits1 Randomdigits2

and I want to match ANYNAME1 , ANYNAME2 , Randomdigits1 and Randomdigits2

So far I am able to match ANYNAME1 in first line using below regex :

_regex_struct = re.compile(r'/begin MEASUREMENT (.*)(.*)\n')

but i am not able to go to the second line. How to match the expression on second line??


Solution

  • I just make an assumption with your input. You may check the RegexDemo.

    inputstr = '''/begin MEASUREMENT ANYNAME1 "Unterstützungskraft Softwaremodul "  
    SWORD ANYNAME2 1 100 -2342342523 2432343535654
    '''
    _regex_struct = re.compile(r'/begin\s+MEASUREMENT\s+(?P<name1>[\w.]+)\W.*\nSWORD\s+(?P<name2>[\w.]+)\W.+\s+(?P<digit1>-\d.+|\d.+)\s+(?P<digit2>-\d.+|\d.+)')
    _regex_struct.findall(inputstr)
    

    Output:

    [('ANYNAME1', 'ANYNAME2', '-2342342523', '2432343535654')]
    

    Explanation of the expression:

    \s = any whitespace character

    (?P<>) = to create a group of the expected output

    \w = any word character

    \W = any non-word character

    \d = any digit

    + = to express one or more