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 perform a zero length match with Python Regex?
- How to replace all using Python regex?
- How to match a hex number with regex in Python?
- How to match an IP address with regex in Python?
- How to get the href attribute value from a regex in Python?
- How to replace a certain group using Python regex?
- How to get all matches from a regex in Python?
- How to regex match excluding a character in Python?
- How to match a float with regex in Python?
- How to match whitespace in Python regex?
See more codes...