Python re.search() Method

Python re 模块Python re Module


re.search()is Pythonremodule used tosearch patternsfunction that, in a string,scans and findsthe first position matching the specified regular expression.

andre.match()Unlike,re.search()It is not required to match from the beginning of the string; it will find a match at any position in the string.

Word Meaning: searchmeans to search and find.


Basic Syntax and Parameters

re.search()is a module-level function, directly throughremodule call.

Syntax Format

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

Parameter Description

  • pattern:
    • Type: string (str)
    • Description: The regular expression pattern to match.
  • string:
    • Type: string (str)
    • Description: The string to be searched, in which to find a match.
  • flags:
    • Type: integer (int, optional)
    • Description: Regular expression flags used to control the matching mode. Such asre.IGNORECASE、re.MULTILINEetc.

Function Description

  • Return Value: If a match is found, returns amatchobject; if no match is found, returnsNone。
  • Effect: Returns the position information of the first match, including the matched content, start position, and end position.

Examples

Let us thoroughly master, through a series of examples from simple to complex,re.search()the usage.

Example 1: Basic Usage - Find the First Match

Example

import re

# Search the string for the first matching number
text = "Python 3.9 is the most commonly used version"
result = re.search(r'\d+\.\d+', text)

if result:
    print("Found match:", result.group())  # Output: 3.9
    print("Match start position:", result.start())  # Output: 7
    print("Match end position:", result.end())  # Output: 10

Expected output:

找到匹配: 3.9
匹配起始位置: 7
匹配结束位置: 10

Code explanation:

  1. r'\d+\.\d+'Matches one or more digits, followed by a dot, then one or more digits (version number format).
  2. re.search()Returns the object of the first match position.
  3. result.group()Returns the matched text content.
  4. result.start()andresult.end()Returns the position index of the match.

Example 2: Find a Match at Any Position

re.search()It can search at any position in the string; this is itsre.match()main difference.

Example

import re

text = "My phone number is 138-1234-5678, his phone number is 139-9876-5432"

# Find the first phone number
result = re.search(r'\d{3}-\d{4}-\d{4}', text)

if result:
    print("First phone number:", result.group())

Expected output:

第一个手机号: 138-1234-5678

Code explanation:

  • \d{3}-\d{4}-\d{4}Matches the Chinese phone number format (3 digits - 4 digits - 4 digits).
  • re.search()Returns as soon as the first match is found; it will not continue searching.

Example 3: Use Flags to Ignore Case

By usingflagsthe parameter, you can change the matching behavior, such as ignoring case.

Example

import re

text = "Python is a Powerful Programming Language"

# Use re.IGNORECASE to ignore case
result = re.search(r'python', text, re.IGNORECASE)

if result:
    print("Found:", result.group())  # Output: Python

Expected output:

找到: Python

Code explanation:

  • re.IGNORECASEMakes matching case-insensitive, so it can match "Python".

Example 4: Extract Group Content

Parentheses()can create groups to extract specific parts of interest.

Example

import re

text = "User email: [email protected]"

# Use groups to extract the username and domain
result = re.search(r'(\w+)@(\w+\.\w+)', text)

if result:
    print("Full match:", result.group())      # [email protected]
    print("Group 1:", result.group(1))    # user
    print("Group 2:", result.group(2))    # example.com

Expected output:

完整匹配: [email protected]
第1个分组: user
第2个分组: example.com

Code explanation:

  • Parentheses()create two groups.
  • result.group(1)andresult.group(2)Extract the content of the two groups respectively.

Python re 模块Python re Module

Other Extensions