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 theremodule 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 patternquickin 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 plus sign in Python regex?
- How to perform a zero length match with Python Regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match whitespace in Python regex?
- How to replace in a file using Python regex?
- How to replace all using Python regex?
- How to match a year with Python Regex?
- How to match a URL using Python regex?
- How to match zero or one occurence in Python regex?
- How to ignore case in Python regex?
See more codes...