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 theremodule 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 aMatchobject if found.if match:: checks if aMatchobject was returned.print(match.group()): prints the string matched by the regular expression.
Helpful links
More of Python Regex
- How to match a plus sign in Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match whitespace in Python regex?
- How to replace all using Python regex?
- How to remove numbers from a string using Python regex?
- How to match a URL using Python regex?
- How to quote in Python regex?
- How to match one or more occurence in Python regex?
- How to match a hex number with regex in Python?
- How to match a URL path using Python regex?
See more codes...