Articles → Python → Regular Expression In Python
Regular Expression In Python
Purpose
Example
import re
# \d+ or [0-9]+ - one or more numbers
# \w+ - Alphanumeric
# \s - white space
# \D - Non-digit
# \W - Non alphanumeric
# \S - Non-whitespace
pattern = r"\d+"
text = "my city pin code is 123456"
for match in re.finditer(pattern, text):
print(match.span())
Identifier Table
Identifier | Meaning | Sample |
---|
\d+ or [0-9]+ | One or more numbers | |
\w+ | Alphanumeric | |
\s | White space | - • Abc cde
- • My name is gyan
|
\D | Non-digit | |
\W | Non-alphanumeric | |
\S | Non-whitespace | |
Various Functions Of Match Object
import re
pattern = "\d+"
text = r"my phone number is 12345"
match = re.search(pattern, text)
print(match.span())
print(match.group())
print(match.start())
print(match.end())
Output
Functions
Function | Purpose |
---|
Span | Returns the tuple of the starting and ending position of the match |
Group | Returns the string matched using regular expression |
Start | Returns the starting position of the match |
End | Returns the ending position of the match |