re.search()

What You'll Learn: In this tutorial, you'll discover how to use the re.search() function to find the first match of a pattern in a string. This function helps you locate specific patterns quickly.

Syntax

The syntax of the re.search() function is:

python
re.search(pattern, string, flags=0)

Parameters

  • pattern (required): The pattern to be found in the string.
  • string (required): The string in which the pattern is to be found.
  • flags (optional): Optional flags like re.IGNORECASE.

Return Value

The function returns a re.Match object if a match is found; otherwise, it returns None.

Examples

  1. Finding a Pattern in a String
    • Example Code:

      python
      import re
      
      pattern = '[a-z]+'
      string = '-----2344-Hello--World!'
      result = re.search(pattern, string)
      print(result)
      
    • Output:

       
      <re.Match object; span=(11, 15), match='ello'>
      
  2. Getting the Matching Text
    • To get the matching text as a string, use the group() method on the re.Match object.
    • Example Code:

      python
      import re
      
      pattern = '[a-z]+'
      string = '-----2344-Hello--World!'
      result = re.search(pattern, string)
      print(result.group())
      
    • Output:

       
      ello
      
  3. Pattern Not in String
    • When the pattern is not present in the string, re.search() returns None.
    • Example Code:

      python
      import re
      
      pattern = '[a-z]+'
      string = '-----2344-HELLO--WORLD!'
      result = re.search(pattern, string)
      print(result)
      
    • Output:

       
      None
      

Try It Yourself: Fun Exercises

  1. Find a Word:
    • Create a string and a pattern representing a word.
    • Use re.search() to find the first occurrence of the word in the string.
  2. Match Digits:
    • Write a string containing numbers and letters.
    • Use re.search() to find the first sequence of digits in the string.

Summary:

In this Python tutorial, we learned how to use the re.search() function to find the first match for a given pattern in a string. This function is useful for locating specific patterns quickly. Keep experimenting and have fun with Python!