The search() function

The search() function of the re module will search through a string. It will look for any location for the specified re pattern. The search() will take a pattern and text and it will search through our specified string for a match. It will return a match object when a match is found. It will return None if no match found. The match object has two methods:

  • group(num): Returns an entire match
  • groups(): Returns all matching subgroups in tuple

The syntax for this function is as follows: 

re.search(pattern, string)

Create a re_search.py script and write following content in it:

import re

pattern = ['programming', 'hello']
str_line = 'Python programming is fun'
for p in pattern:
print("Searching for %s in %s" % (p, str_line))
if re.search(p, str_line):
print("Match found")
else:
print("No match found")

Run the script and you will get the output as follows:

student@ubuntu:~/work$ python3 re_search.py
Searching for programming in Python programming is fun
Match found
Searching for hello in Python programming is fun
No match found

In the preceding example, we used the search() method of match object to find the re pattern. After importing the re module, we specified the pattern in a list. In that list, we wrote two strings: programming and hello. Next, we created a string: Python programming is fun. We wrote a for loop that will check for a specified pattern one by one. If a match is found, the if block will be executed. If no match is found, the else block will be executed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset