简体   繁体   English

python:用于匹配多行模式的正则表达式(应用于字符串的开头)

[英]python: regex to match pattern on multiple lines (apply to start of string)

I'm trying to create a pattern to match two lines in the following multi-line text:我正在尝试创建一个模式来匹配以下多行文本中的两行:

Text of no interest.
TextOfInterest1, foobar of no interest
another foobar of no interest
AnotherText-of_Interest2 some foobar don't care

I need to match exactly TextOfInterest1 and AnotherText-of_Interest2 , note that there might be multiple lines between TextOfInterest1 and AnotherText-of_Interest2 .我需要精确匹配TextOfInterest1AnotherText-of_Interest2 ,注意TextOfInterest1AnotherText-of_Interest2之间可能有多行。 I don't know how I can apply ^ symbol more than once in a single pattern string?我不知道如何在单个模式字符串中多次应用^符号?

Try this:尝试这个:

pat = r"^.*\n([-_\w]+).*\n.*\n([-_\w]+).*$"
string="""Text of no interest.
TextOfInterest1, foobar of no interest
another foobar of no interest
AnotherText-of_Interest2 some foobar don't care"""

re.search(pat,string).groups()
('TextOfInterest1', 'AnotherText-of_Interest2')

Check pattern at regex101 .检查regex101处的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM