python-regexHow to match everything between two words with Python regex?
To match everything between two words with Python regex, you can use the re.findall()
function. This function takes a regular expression pattern and a string as arguments and returns a list of all non-overlapping matches of the pattern in the string.
For example, to match everything between two words start
and end
, you can use the following code:
import re
text = "This is a start sentence. This is an end sentence."
matches = re.findall(r"start(.*?)end", text)
print(matches)
The output of the above code will be:
[' sentence. This is an ']
The code consists of the following parts:
import re
: This imports there
module which provides regular expression matching operations.text = "This is a start sentence. This is an end sentence."
: This is the string in which we will search for the pattern.matches = re.findall(r"start(.*?)end", text)
: This uses there.findall()
function to search for the patternstart(.*?)end
in the stringtext
. The.*?
part of the pattern matches any character (.
) zero or more times (*
) in a non-greedy manner (?
).print(matches)
: This prints the list of matches found by there.findall()
function.
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to perform a zero length match with Python Regex?
- How to use word boundaries in Python Regex?
- How to match a year with Python Regex?
- How to match whitespace in Python regex?
- How to match a URL path using Python regex?
- How to quote in Python regex?
- How to match one or more occurence in Python regex?
- How to use negative lookbehind in Python regex?
- How to match HTML tags with regex in Python?
See more codes...