(toc) #title=(Table of Contact)
What is Regular Expression?
* A Regular Expression (RegEx) is a sequence of characters that define a search pattern.
* For using Regular Expression import re module.
* There are two types of function:
1) Match function
2) Search function
What is Match Function?
* This function determines if the RE matches at the beginning of the string.
* Syntax: re.match(pattern, string)
* Pattern: This the regular expression to be matched
* String: This is the string, which would be searched to match the pattern at the beginning of string.
Program 1)
import re
pattern = r"^abc"
mystring = "abcde"
x = re.match(pattern,mystring)
print(x)
Output = <re.match object; span= (0, 3), match='abc'>
Program 2)
import re
pattern = r"^abc"
mystring = "acde"
x = re.match(pattern,mystring)
print(x)
Output = None
What is Search Function?
* Scan through a string, looking for any location where this RE matches.
* Syntax: re.search(pattern, string)
* Pattern: This the regular expression to be matched
* String: This is the string, which would be searched to match the pattern at the beginning of string.
Program 3)
import re
txt = "We are learning Python"
x = re.search("\s", txt) #This expression is written for searching whitespace
print("First Space: ", x)
Output = First Space: <re.match object; span= (2,3), match=' '>
Program 4)
import re
txt = "We are learning Python"
x = re.search("\s", txt) #This expression is written for searching whitespace
print("First Space: ", x.start)
Output = First Space: 2
Program 5)
import re
txt = "We are learning Python"
x = re.search("Java", txt)
print(x)
Output = None
What is Replace Function?
* Python regex offers sub() the subn() methods to search and replace patterns in string. Using these methods, we can replace one or more occurrences of a regex pattern in the target string with a substitute string.
* Syntax: re.sub(pattern, repl, string)
Program 6)
import re
str1= "My name is hrsikh"
print("Before replace: ", str1)
result = re.sub(r"hrsikh", "website", str1)
print("After replace: ", result)
Output = Before replace: My name is hrsikh
After replace: My name is website