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



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



Output


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



Functions


FunctionPurpose
SpanReturns the tuple of the starting and ending position of the 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 4, 2020

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250