Menu
Coddy logo textTech

search

Lesson 3 of 28 in Coddy's RegEx in Python course.

While the findall function returns all matches in a list, the search function searches the string for a pattern and returns the first occurrence as a match object.

re.search(pattern, string)
  • pattern: The regular expression pattern you want to search for.
  • string: The string in which you want to search for the pattern.
import re

text = "Hello, world!"
pattern = "world"

match = re.search(pattern, text)

if match:
    print("Match found:", match.group())  # Output: Match found: world
else:
    print("No match found")

In the above example, we searched for the word "world" in the string text. The search function returns a match object, and we use the group() method to extract the matched text.

challenge icon

Challenge

Easy

Write a program that uses the search function to check if the string s contains the word w. Print "Found" if the word is present, otherwise print "Not found".

Try it yourself

import re

s = input()
w = input()

# Write code here

All lessons in RegEx in Python