Menu Close

Searching – Regular Expressions (Regex) Python…..FcukTheCode

Python makes regular expressions available through the re module.

For the first part in using regular expressions and matching the string
you can visit this link –> Matching the beginning of a string (Regex) Regular Expressions in python

The re.search() method takes a regular expression pattern and a string and searches for that pattern within the string. If the search is successful, search() returns a match object or None otherwise.

pattern = r"(your base)"
sentence = "All your base are belong to us."
match = re.search(pattern, sentence)
print(match.group(1))
# Output: 'your base'


match = re.search(r"(belong.*)", sentence)
print(match.group(1))
# Output: 'belong to us.'

OUTPUT:
your base
belong to us

ILLUSTRATION EXAMPLE (using the command line)

Executed using python3
executed using python3

Searching is done anywhere in the string unlike re.match . You can also use re.findall .
You can also search at the beginning of the string (use ^ ),

match = re.search(r"123$", "zzb123")
match.group(0)
# Out: '123'
match = re.search(r"123$", "123zzb")
match is None
# Out: True

or both (use both ^ and $ ):

match = re.search(r"^123$", "123")
match.group(0)
# Out: '123'

ILLUSTRATION: refer the code below

executed using python3