Today, I will take a new part of Python for my tutorial series. In this part you will learn Exception Handling.
I already told you the following:
Python language has very good functions for Regular function and there regular expression also useful for searching text from any statement.
Today I will give you some examples of regular expression that may help you easily learn the concept of regular expression according to python. Microsoft Word also has regular expression technique for searching text in whole document like the below Image.
Regular Expression Syntax
- \s — White space characters
- \S — Non-white space characters
- \w — Word characters
- \W — Non-word characters
- \d — Digit characters
- \D — Non-digit characters
Methods and Attributes for search characters
- match() - Determine if the RE matches at the beginning of the string.
- search() - Scan through a string, looking for any location where this RE matches.
- findall()- Find all substrings where the RE matches, and returns them as a list.
- finditer()- Find all substrings where the RE matches, and returns them as an iterator.
Methods and Attributes for match object instances
- group() Return the string matched by the RE
- start() Return the starting position of the match
- end() Return the ending position of the match
- span() Return a tuple containing the (start, end) positions of the match
- Now I’m giving you some example of regular expressions in Python.
import re
message = 'call me at 9785959495'
regex = re.compile(r'\d+')
number = regex.search(message)
print(number.group())
Output : 9785959495
According to the above Example show library re is useful for finding numbers in message. r’\d+’ here r denotes this is a line and r does not perform escape convertion like \d and \d means search digits and + means total digits.
- Getting All digits from particular statements
import re
message = 'call me at 9785959495 or 9929892278'
regex = re.compile(r'\d+')
number = regex.findall(message)
print(number)
Output : ['9785959495', '9929892278']
- Getting in multiple groups value
message = 'call me at 9785959495-9929892278'
regex = re.compile(r'(\d+)-(\d+)')
number = regex.search(message)
number.group()
Output : '9785959495-9929892278'
number.group(1)
Output : 9785959495
number.group(2)
Output : 9929892278
Python has many methods for regular expression techniques to find or search characters in regular expression library.