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())






Picture showing the match object when numbers are found in string

Click to Enlarge


Identifier table


IdentifierMeaningSample
\d+ or [0-9]+One or more numbers
  • • 210
  • • 45
  • • 45673
\w+Alphanumeric
  • • Abc2
  • • Y56s
\sWhite space
  • • Abc cde
  • • My name is gyan
\DNon-digit
  • • Abc
  • • lkl@
\WNon alphanumeric
  • • %%%%**
\SNon-whitespace
  • • hsakshkahsk22



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())




Picture showing the output of span, group, start and end function

Click to Enlarge



FunctionPurpose
SpanReturns the tuple of starting and ending position of match
GroupReturns the string matched using regular expression.
StartReturns the starting position of the match
EndReturns the ending position of the match



Posted By  -  Karan Gupta
 
Posted On  -  Saturday, July 04, 2020

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250