Regular Expression is also known as RegEx.It is also used for pattern matching and search pattern.
re is built-in package in python.
import re
import re string='Python Programming SmallCode' print("For First Search:") s1=re.search("^P.*e$",string) print(s1) print("For Second Search:") s2=re.search("^k.*t$",string) print(s2)Output
For First Search: <re.Match object; span=(0, 28), match='Python Programming SmallCode'> For Second Search: None
S.No |
break |
---|---|
. |
It matches any character except newline. |
{ } |
It matches Exactly the specified number of occurrences |
[ ] |
It matches a set of characters. |
^ |
It matches starting with character or string. |
$ |
It matches ends with character or string. |
* |
It matches zero or more occurrence. |
+ |
It matches one or more occurrence. |
Search() fuction are used to search the sequence and return the number of occurrence.
Examplest="Python Programming by SmallCode" print("For First Search:") y = re.search("\s", st) print(y)Output
For First Search: <re.Match object; span=(6, 7), match=' '>
findall() fuction returns the list of all matches in any sequences and if there is no match then it return empty list.
Exampleimport re string='Python Programming by SmallCode' s1=re.findall("P",string) print("Matched List 1:",s1) s2=re.findall("SM",string) print("Matched List 2:",s2)Output
Matched List 1: ['P', 'P'] Matched List 2: []
sub() replace the some character or string with some character or string.
Exampleimport reOutput
string='Python Programming By SC' s1=re.sub("SC","SmallCode",string) print("After Replacing:",s1)
After Replacing: Python Programming By SmallCode
split() function split the sequence and return in the form of list.
Exampleimport re string='Python Programming By SmallCode' s1=re.split(" ",string) print("After spliting:",s1)Output
After spliting: ['Python', 'Programming', 'By', 'SmallCode']
split() function split according to number of occurrence.
Exampleimport re string='Python Programming By SmallCode' s1=re.split(" ",string,3) print("After spliting:",s1)Output
After spliting: ['Python', 'Programming', 'By', 'SmallCode']