VOOZH about

URL: https://www.geeksforgeeks.org/python/re-search-in-python/

⇱ re.search() in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

re.search() in Python

Last Updated : 23 Jul, 2025

re.search() method in Python helps to find patterns in strings. It scans through the entire string and returns the first match it finds. This method is part of Python's re-module, which allows us to work with regular expressions (regex) simply. Example:


Output
Yes

Explanation: This code searches the entire string to find if the pattern "welcome" exists. If a match is found, it confirms the presence by printing "Yes" otherwise, it prints "No".

Syntax of re.search()

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

Parameters:

  • pattern: A regex pattern to search for; can be simple text or a complex expression.
  • string: The target string where the pattern is searched.
  • flags (optional): Modifiers that change matching behavior (e.g., case-insensitive); default is 0.

Returns:

  • Match object: Returned if a match is found; provides methods like .group() and .start().
  • None: Returned if no match is found.

Examples of re.search()

Example 1: In this example, we search for the first number that appears in a given string using a regular expression. It support special characters like \d for digits, \w for word characters and more, allowing us to search for complex patterns efficiently.


Output
2

Explanation: This code searches for the first occurrence of one or more digits in the string. The pattern \d+ matches one or more digits and re.search() returns the first match it finds.

Example 2: In this example, we search for a phone number in a string using a regular expression pattern. A match object returned by the search provides useful methods like group() to get the matched text and start() to find the starting index of the match in the original string.


Output
123-456-7890
19

Explanation: This pattern matches a phone number in the format 123-456-7890. The group() method returns the matched string and start() gives the index at which the match begins.

Example 3: In this example, we want to check whether the given string begins with a capital letter (A–Z). We're using the re.search() function along with a regular expression pattern that looks for a capital letter at the beginning of the string.


Output
V

Explanation: This pattern ^[A-Z] checks if the string starts with an uppercase letter. If it does, group() returns that letter otherwise, "No" is printed.

Related Articles:

Comment
Article Tags: