Regular Expression in Python
In this tutorial, we will focus on Regular expression in Python with some examples.
Regular Expression in Python with examples
A regular expression is a group of a special sequence of characters that can be used to match or detect other strings.
Many basic patterns can be easily tackled using these special characters.
Regular Expression -Character classes: in Python
1.[abc] =could be a ,b or c 2.[^abc] = Except a , b or c 3.[a-z] = Any lower case alphabet symbol 4.[A-Z] = Any upper case alphabet symbol 5.[a-zA-z] Any alphabet symbols 6.[0-9] = any digits from 0 to 9 7.[a-zA-Z0-9] - Any alphanumeric character 8.[^a-zA-Z0-9] - Except alphanumeric character (special character). 9. \s - Space character 10.\S - Any character Except space character 11.\d - Any digit from 0 to 9 12.\D - any character except digit 13.\w - any word character[a-zA-Z0-9] 14.\W - Any character except word character (Special character).
Various methods of Regular Expression-
- re.match()
- re.search()
- re.findall()
- re.split()
- re.sub()
- re.compile()
Example-
Valid mail id or not- Regular expression
import re choice="y" while choice=="y": email =input("Enter email id") match = re.match('^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z]+(\.[a-z]+)*(\.[a-z]{2,4})$', email) if match == None: print('Bad Syntax') else: print("valid mail id")
Output-
Enter email id-123gmail.com Bad Syntax Enter email [email protected] valid mail id
Example 2 Regular expression
import re result = re.search('Code', 'Code Speedy') print (result.group(0))
Output-
Code
Example 3
import re result = re.findall('Earth', 'Earth is large and Earth is unique') print (result)
Output- ['Earth', 'Earth']
Example 4
import re result=re.split('e','Code Speedy') print(result)
Output-
['Cod', ' Sp', '', 'dy']
Example 5-
import re result=re.split('h','Earth is round') print(result)
Output: ['Eart', ' is round']
Example 6-
import re obj=re.compile('kanto') result=obj.findall('Ash is from kanto') print (result) result2=obj.findall('kanto is largest region of all') print (result2)
Output:
['kanto'] ['kanto']
Return the first two character of each word- in Python using Regular expression
import re
result=re.findall(\w\w','Largest community of India')
print (result)
Output-
['la', 'rg', 'es', 'co', 'mm', 'un', 'it', 'of', 'In', 'di']
^ symbols-
We can use ^ symbol to check whether the given target string starts with our provided patters or not.
import re s="Learning Python is very easy" res=re.search("^Learn",s) if res!=None: print("Target String starts with Learn") else: print("Target String not starts with Learn")
$ symbol-
We can use the $ symbol to check whether the given target string ends with our provided pattern or not.
import re s="Learning Python is very easy" res=re.search("easy$",s) if res!=None: print("Target String ends with easy") else: print("Target String not ends with easy")
You may also read:
Leave a Reply