InterviewSolution
Saved Bookmarks
| 1. |
Python RegEx |
||||||||||||||||||||||||||||||||
Answer»
The re module in python allows us to perform regex matching operations. import relandline = re.compile(r'\d\d\d\d-\d\d\d\d') num = landline.search('LandLine Number is 2435-4153') print('Landline Number is: {}'.format(num.group())) Output: Landline Number is: 2435-4153 The above example landline number from the string and stores it appropriately in the num variable using regex matching.
A group is a part of a regex pattern enclosed in parenthesis (). We can put matches into different groups using the parenthesis (). We can access the groups using group() function. import relandline = re.compile(r'(\d\d\d\d)-(\d\d\d\d)') num = landline.search('LandLine Number is 2435-4153') # This will print the first group, which is the entire regex enclosed in the brackets print(num.group(0)) # This will print the second group, which is the nested regex enclosed in the 1st set of nested brackets print(num.group(1)) # This will print the third group, which is the nested regex enclosed in the 2nd set of nested brackets print(num.group(2)) Output: 2435-4153 2435 4153
There are a lot of regex symbols that have different functionalities so they are mentioned in the table below:
Example: Here we define a regex pattern, address = "(\\d*)\\s?(.+),\\s(.+)\\s([A-Z]{2,3})\\s(\\d{4})"From the above table, we can explain some of the symbols in this pattern:
|
|||||||||||||||||||||||||||||||||