python-regexHow to find the first match with regex in Python?
The re
module in Python provides a re.search()
function to find the first match of a pattern in a string.
Example code
import re
string = 'The quick brown fox jumps over the lazy dog.'
match = re.search(r'quick', string)
if match:
print('Found match:', match.group())
Output example
Found match: quick
Code explanation
import re
: imports there
module which provides there.search()
functionstring = 'The quick brown fox jumps over the lazy dog.'
: defines the string to searchmatch = re.search(r'quick', string)
: searches for the patternquick
in the stringif match:
: checks if a match was foundprint('Found match:', match.group())
: prints the found match
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to match a URL path using Python regex?
- How to match a year with Python Regex?
- How to match a UUID using Python regex?
- How to match whitespace in Python regex?
- How to remove numbers from a string using Python regex?
- How to replace in a file using Python regex?
- How to replace all using Python regex?
- How to perform a zero length match with Python Regex?
See more codes...