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 theremodule 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(.*?)endin 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 use word boundaries in Python Regex?
- How to use named groups with regex in Python?
- How to perform a zero length match with Python Regex?
- How to match a question mark in Python regex?
- How to match a plus sign in Python regex?
- How to match whitespace in Python regex?
- How to replace all using Python regex?
- How to match HTML tags with regex in Python?
- How to use quantifiers in Python regex?
- How to match any symbol except a given one with Python regex?
See more codes...