一、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 <js@example.com>"
pattern = "^From: (.*) <.*>$"
result = re.search(pattern, str)
if result:
print("Match found:", result.group(1))
else:
print("No match found.")