正则表达式匹配python中的多行

时间:2015-01-15 12:43:08

标签: python regex

我是一个新的python用户。编写一些代码以匹配具有正则表达式的多行方案。但无法得到答案。如果我遗失了什么,有人可以帮助我。

我尝试了pythex.org并且匹配了所需的两行。但是当我尝试使用代码时

a = """
 MEG        Type     EntityId Level PrimVlan CC Inter(ms) CC Priority CC EnaStatus
---------- -------- -------- ----- -------- ------------ ----------- ------------
meg401     lsp      1        4     3        3.3          6           enable

MEP ID     Type     EntityId Level Intf    RMEP ID  Direction Active Status
---------- -------- -------- ----- ------- -------- --------- -------------
meg401        lsp      1        4     0/5     451      down      disable
"""

result = re.match("meg401(.*)",a,re.M)

print result

失败了。感谢对此的任何建议!

2 个答案:

答案 0 :(得分:4)

来自docs

  

请注意,即使在MULTILINE模式下,re.match()也只会匹配字符串的开头而不是每行的开头。

使用search代替

result = re.search("meg401(.*)",a,re.M)

作为建议,因为您有多个匹配值,请使用findall

result = re.findall("meg401(.*)",a,re.M)

答案 1 :(得分:2)

result = re.findall("meg401(.*)",a,re.M)

使用re.findall而非re.match

re.match匹配字符串的开头。

参见演示。

https://regex101.com/r/tX2bH4/7#python

相关问题