python search regex code example

Example 1: Using the Python string below to perform a search using a regular expression that you create. search_string=’’’This is a string to search for a regular expression like regular expression or regular-expression or regular:expression or regular&expression’’’

match1 = re.findall(pattern, search_string)
if match1 != None:
  print(pattern + 'matched')
else:
  print(pattern + 'did not match')

Example 2: python re compile

import re
#	Compile a regular expression pattern into a regular expression object, which can be used for matching using its match(), search() and other methods, described below.

prog = re.compile(pattern)
result = prog.match(string)

#	is equivalent to

result = re.match(pattern, string)

Example 3: regex in python

# pip install regex
import re
# simple find all
sample = "Nothing lasts... but nothing is lost"
found = re.findall("thing", sample)
print(found)

Example 4: re.sub in python example

import re

result = re.sub(pattern, repl, string, count=0, flags=0);