Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match text between two strings with regular expression

I would like to use a regular expression that matches any text between two strings:

Part 1. Part 2. Part 3 then more text 

In this example, I would like to search for "Part 1" and "Part 3" and then get everything in between which would be: ". Part 2. "

I'm using Python 2x.

like image 232
Carlos Muñiz Avatar asked Sep 20 '15 13:09

Carlos Muñiz


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

How do I match any character across multiple lines in a regular expression?

So use \s\S, which will match ALL characters.


2 Answers

Use re.search

>>> import re >>> s = 'Part 1. Part 2. Part 3 then more text' >>> re.search(r'Part 1\.(.*?)Part 3', s).group(1) ' Part 2. ' >>> re.search(r'Part 1(.*?)Part 3', s).group(1) '. Part 2. ' 

Or use re.findall, if there are more than one occurances.

like image 174
Avinash Raj Avatar answered Oct 15 '22 22:10

Avinash Raj


With regular expression:

>>> import re >>> s = 'Part 1. Part 2. Part 3 then more text' >>> re.search(r'Part 1(.*?)Part 3', s).group(1) '. Part 2. ' 

Without regular expression, this one works for your example:

>>> s = 'Part 1. Part 2. Part 3 then more text' >>> a, b = s.find('Part 1'), s.find('Part 3') >>> s[a+6:b] '. Part 2. ' 
like image 29
lord63. j Avatar answered Oct 15 '22 23:10

lord63. j