简体   繁体   中英

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 . 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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