Python regex match across multiple lines

岁酱吖の 提交于 2019-12-11 13:00:33

问题


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)

回答1:


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

  • (?sm) - re.DOTALL and re.M are on
  • ^ - start of a line
  • Example= - a substring
  • (.*?) - Group 1: any 0+ chars, as few as possible
  • (?=[\r\n]+\w+=|\Z) - a positive lookahead that requires the presence of 1+ CR or LF symbols followed with 1 or more word chars followed with a = sign, or end of the string (\Z).

See the regex demo.



来源:https://stackoverflow.com/questions/50137113/python-regex-match-across-multiple-lines

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