Sometimes, we want to find string between two substrings with Python.
In this article, we’ll look at how to find string between two substrings with Python.
How to find string between two substrings with Python?
To find string between two substrings with Python, we call the re.search
method with a regex that matches strings between 2 substrings.
For instance, we write
import re
s = 'asdf=5;iwantthis123jasd'
result = re.search('asdf=5;(.*)123jasd', s)
print(result.group(1))
to call re.search
with a regex string to match the strings that are between asdf and 123jasd in the string s
.
Then we call result.group
to get the match.
Conclusion
To find string between two substrings with Python, we call the re.search
method with a regex that matches strings between 2 substrings.