Match text between two strings with regular expression

PythonRegexPython 2.x

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCarlos MuñizView Question on Stackoverflow
Solution 1 - PythonAvinash RajView Answer on Stackoverflow
Solution 2 - Pythonlord63. jView Answer on Stackoverflow