Match Object
A Match object contains all the information about the search and the result and if there is no match found then None will be returned. Let’s see some of the commonly used methods and attributes of the match object.
1. Getting the string and the regex
match.re attribute returns the regular expression passed and match.string attribute returns the string passed.
Example: Getting the string and the regex of the matched object
The code searches for the letter “G” at a word boundary in the string “Welcome to w3wiki” and prints the regular expression pattern (res.re
) and the original string (res.string
).
Python3
import re s = "Welcome to w3wiki" res = re.search(r "\bG" , s) print (res.re) print (res.string) |
re.compile('\\bG') Welcome to w3wiki
2. Getting index of matched object
- start() method returns the starting index of the matched substring
- end() method returns the ending index of the matched substring
- span() method returns a tuple containing the starting and the ending index of the matched substring
Example: Getting index of matched object
The code searches for the substring “Gee” at a word boundary in the string “Welcome to w3wiki” and prints the start index of the match (res.start()
), the end index of the match (res.end()
), and the span of the match (res.span()
).
Python3
import re s = "Welcome to w3wiki" res = re.search(r "\bGee" , s) print (res.start()) print (res.end()) print (res.span()) |
11 14 (11, 14)
3. Getting matched substring
group() method returns the part of the string for which the patterns match. See the below example for a better understanding.
Example: Getting matched substring
The code searches for a sequence of two non-digit characters followed by a space and the letter ‘t’ in the string “Welcome to w3wiki” and prints the matched text using res.group()
.
Python3
import re s = "Welcome to w3wiki" res = re.search(r "\D{2} t" , s) print (res.group()) |
me t
In the above example, our pattern specifies for the string that contains at least 2 characters which are followed by a space, and that space is followed by a t.
Reference:
https://docs.python.org/2/library/re.html
We have discussed RegEx in Python, we have gone through the metacharacters, functions and special sequences in RegEx Python.
Regular Expression is a very important concept in Python, we have tried to explain it in a easy way. Hope it helps in your Python Journey!!
Regular Expression (RegEx) in Python with Examples
A Regular Expression or RegEx is a special sequence of characters that uses a search pattern to find a string or set of strings.
It can detect the presence or absence of a text by matching it with a particular pattern and also can split a pattern into one or more sub-patterns.