Python - AI 助手

Python re.search() 方法



Python 的re.search()方法用於在一個字串中搜索模式。它掃描整個字串,如果在字串中的任何位置找到模式,則返回一個匹配物件。

re.match()方法不同,後者只檢查字串開頭的匹配,而re.search()則在字串中的任何位置查詢匹配。如果找到匹配項,則返回匹配物件;否則返回'None'。

此方法對於查詢字串中的模式很有用,而不管其位置如何,從而允許更靈活的模式匹配和從文字資料中提取資訊。

語法

以下是 Python re.search()方法的語法和引數:

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

引數

以下是 python re.search()方法的引數:

  • pattern: 要搜尋的正則表示式模式。
  • string: 要在其內搜尋的輸入字串。
  • flags(可選): 這些標誌控制搜尋的行為。它可以是各種標誌的按位或組合,例如 re.IGNORECASE、re.MULTILINE 等。

返回值

如果在字串中找到模式,此方法返回匹配物件;否則返回 None。

示例 1

以下是使用re.search()方法的基本示例。這裡在字串“Hello, world!”中搜索模式“world”:

import re

pattern = re.compile(r'\d+')
match = pattern.match('123abc')
if match:
    print(match.group())  

輸出

123

示例 2

在此示例中,模式 '\d+-\d+-\d+' 用於匹配日期格式,並使用捕獲組分別提取年份、月份和日期:

import re

result = re.search(r'(\d+)-(\d+)-(\d+)', 'Date: 2022-01-01')
if result:
    print("Year:", result.group(1))  
    print("Month:", result.group(2)) 
    print("Day:", result.group(3))  

輸出

Year: 2022
Month: 01
Day: 01

示例 3

在此示例中,?<=good 是一個正向先行斷言,它檢查 'good' 是否存在於 'morning' 之前,而不將其包含在匹配項中:

import re

result = re.search(r'(?<=good )morning', 'Have a good morning!')
if result:
    print("Pattern found:", result.group())  

輸出

Pattern found: morning
python_modules.htm
廣告