python-regexHow to get a group from a regex in Python?
To get a group from a regex in Python, you can use the re.search()
method. This method takes a regular expression pattern and a string and searches for that pattern within the string. If the pattern is found, it returns a Match
object. The Match
object has a group()
method which returns the string matched by the regular expression.
Example code
import re
string = 'The quick brown fox jumps over the lazy dog.'
pattern = r'(quick|lazy)'
match = re.search(pattern, string)
if match:
print(match.group())
Output example
quick
Code explanation
import re
: imports there
module which contains there.search()
method.string = 'The quick brown fox jumps over the lazy dog.'
: creates a string to search for the pattern.pattern = r'(quick|lazy)'
: creates a regular expression pattern to search for.match = re.search(pattern, string)
: searches for the pattern within the string and returns aMatch
object if found.if match:
: checks if aMatch
object was returned.print(match.group())
: prints the string matched by the regular expression.
Helpful links
More of Python Regex
- How to match a year with 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 UUID using Python regex?
- How to replace all using Python regex?
- How to ignore case in Python regex?
- How to match a question mark in Python regex?
- How to use negative lookbehind in Python regex?
- How to match a hex number with regex in Python?
- How to get a number from a string with regex in Python?
See more codes...