Python Language / Python Regular Expression

Python regular expression package re is used check if a string contains the specified search pattern / not.

Sample Programs Output

# To Check if string starts with "Welcome" and ends with "expressions"

import re
textstring = "Welcome to python regular expressions"
vn = re.search("^Welcome.*expressions$", textstring)

if (vn):
  print("String matched!")
else:
  print("String Not match")

String matched!
# findall() to return a list contains all matched.

import re
txt = "Welcome to python regular expressions"
vn = re.findall("re", txt)
print(vn)

['re', 're']

#Return an empty list if no match was found

import re
txt = "Welcome to python regular expressions"
vn = re.findall("java", txt)
print(vn)

[]
#Search() for the first white-space character in the string

import re
txt = "Welcome to python regular expressions"
x = re.search("\s", txt)
print("First white space character located at position:", x.start())

First white space character located at position: 7
# Make a search that returns no match

import re
txt = "Welcome to python regular expressions"
vn = re.search("java", txt)
print(vn)

None

# split() returns a list where the string has been split at each match
import re
txt = "Welcome to python regular expressions"
vn = re.split("\s", txt)
print(vn)

['Welcome', 'to', 'python', 'regular', 'expressions']

import re
txt = "Welcome to python regular expressions"
vn = re.split("\s", txt, 1)
print(vn)

['Welcome', 'to python regular expressions']

#sub()replaces character matches with the text of your given

import re txt = "Welcome to python regular expressions"
vn = re.sub("\s",  "9", txt)
print(vn)

Welcome9to9python9regular9expressions

# Replace the first 2 occurrences with a character

import re
txt = "Welcome to python regular expressions"
vn = re.sub("\s",  "9", txt, 2)
print(vn)

Welcome9to9python regular expressions


Home     Back