一、search函數簡介
re庫是Python提供的正則表達式處理模塊,而search函數是其中的一種匹配模式。search函數會在整個字符串中搜索給定的正則表達式,一旦找到匹配的部分就停止搜索並返回匹配對象Match object。
Match object包含了匹配的字符串、匹配開始和結束位置等等信息。而如果沒有找到匹配的部分,search函數將返回None。
import re str = "Hello world! It's a beautiful day!" pattern = "beautiful" result = re.search(pattern, str) if result: print("Match found:", result.group()) else: print("No match found.")
二、Match object屬性
除了包含被匹配的字符串,Match object還有許多其他有用的屬性。
1、group()
group()函數返回被匹配到的字符串。
import re str = "Hello world! It's a beautiful day!" pattern = "beautiful" result = re.search(pattern, str) if result: print("Match found:", result.group()) else: print("No match found.")
2、start()
start()函數返回匹配字符串在原字符串中的開始位置。
import re str = "Hello world! It's a beautiful day!" pattern = "beautiful" result = re.search(pattern, str) if result: print("Match found at index:", result.start()) else: print("No match found.")
3、end()
end()函數返回匹配字符串在原字符串中的結束位置。
import re str = "Hello world! It's a beautiful day!" pattern = "beautiful" result = re.search(pattern, str) if result: print("Match ends at index:", result.end()) else: print("No match found.")
4、span()
span()函數返回匹配字符串在原字符串中的開始和結束位置。
import re str = "Hello world! It's a beautiful day!" pattern = "beautiful" result = re.search(pattern, str) if result: print("Match starts at index:", result.span()[0]) print("Match ends at index:", result.span()[1]) else: print("No match found.")
三、正則表達式的應用
正則表達式是處理字符串的強大工具,因為它允許我們根據模式匹配字符串,而不僅僅是匹配特定字符。
1、使用通配符
通配符是正則表達式中用於匹配任何字符的特殊字符。點號(.)是最基本的通配符,它匹配除了換行符以外的任何字符。
import re str = "Hello world! It's a beautiful day! How are you?" pattern = ".eautiful" result = re.search(pattern, str) if result: print("Match found:", result.group()) else: print("No match found.")
2、使用字符集
字符集是用於匹配一組字符中的任意一個字符的特殊字符。使用方括號([])表示字符集。
import re str = "Hello world! It's a beautiful day! How are you?" pattern = "[bh]." result = re.search(pattern, str) if result: print("Match found:", result.group()) else: print("No match found.")
3、使用元字符
元字符是正則表達式中有特殊含義的字符。其中最常用的元字符是^和$,它們分別表示匹配字符串的開頭和結尾。
import re str = "Hello world! It's a beautiful day! How are you?" pattern = "^H.*u\?$" result = re.search(pattern, str) if result: print("Match found:", result.group()) else: print("No match found.")
4、使用分組
分組可以將正則表達式中的子模式分組,以便更好地控制匹配結果。使用圓括號(())表示分組。
import re str = "From: John Smith " pattern = "^From: (.*) $" result = re.search(pattern, str) if result: print("Match found:", result.group(1)) else: print("No match found.")
原創文章,作者:XUFF,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/149412.html