regexpython-3.xmultiline

Python regex match across multiple lines


I am trying to match a regex pattern across multiple lines. The pattern begins and ends with a substring, both of which must be at the beginning of a line. I can match across lines, but I can't seem to specify that the end pattern must also be at the beginning of a line.

Example string:

Example=N      ; Comment Line One error=

; Comment Line Two.

Desired=

I am trying to match from Example= up to Desired=. This will work if error= is not in the string. However, when it is present I match Example=N ; Comment Line One error=

config_value = 'Example'
pattern = '^{}=(.*?)([A-Za-z]=)'.format(config_value)
match = re.search(pattern, string, re.M | re.DOTALL)

I also tried:

config_value = 'Example'
pattern = '^{}=(.*?)(^[A-Za-z]=)'.format(config_value)
match = re.search(pattern, string, re.M | re.DOTALL)

Solution

  • Your pattern contains .*? and your options include re.DOTALL (also, re.S is its equivalent) that makes the . match newlines, too. For those of you who wonder why your regex does not match across multiple lines, check these first:

    More references:

    Now, for this concrete case in the OP, you may use

    config_value = 'Example'
    pattern=r'(?sm)^{}=(.*?)(?=[\r\n]+\w+=|\Z)'.format(config_value)
    match = re.search(pattern, s)
    if match:
        print(match.group(1))
    

    See the Python demo.

    Pattern details

    See the regex demo.