面试题答案
一键面试功能区别
- search函数:在整个字符串中搜索匹配正则表达式的第一个位置。它会扫描整个字符串,一旦找到匹配就停止。
- match函数:只从字符串的开头开始匹配正则表达式。如果字符串开头不匹配,则返回None。
匹配规则区别
- search函数:匹配整个字符串内任意位置的内容。
- match函数:严格要求从字符串的起始位置开始匹配。
返回值区别
- search函数:如果找到匹配,返回一个
Match
对象,该对象包含了匹配的相关信息,如匹配的内容、位置等;如果没有找到匹配,则返回None
。 - match函数:如果在字符串开头匹配成功,返回一个
Match
对象;否则返回None
。
示例代码
- search函数示例
import re
text = "hello world, 123"
pattern = r'\d+'
match_obj = re.search(pattern, text)
if match_obj:
print(f"匹配内容: {match_obj.group()}")
print(f"匹配起始位置: {match_obj.start()}")
print(f"匹配结束位置: {match_obj.end()}")
else:
print("未找到匹配内容")
- match函数示例
import re
text = "hello world, 123"
pattern = r'hello'
match_obj = re.match(pattern, text)
if match_obj:
print(f"匹配内容: {match_obj.group()}")
print(f"匹配起始位置: {match_obj.start()}")
print(f"匹配结束位置: {match_obj.end()}")
else:
print("未找到匹配内容")
上述match
函数示例中,如果将pattern
改为r'world'
,由于world
不在字符串开头,将返回None
。而search
函数只要字符串内存在world
就能匹配到。