解释 Python 正则表达式搜索与匹配
re.match() 和 re.search() 都是 Python 模块 re 的方法。
re.match() 方法在字符串开头匹配成功时返回匹配。例如,对字符串“TP Tutorials Point TP”调用 match() 并查找模式“TP”将匹配。
示例
result = re.match(r'TP', 'TP Tutorials Point TP') print result.group(0)
输出
TP
re.search() 方法类似于 re.match(),但不会限制我们在字符串开头查找匹配。
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
示例
result = re.search(r'Tutorials', 'TP Tutorials Point TP') print result.group(0)
输出
Tutorials
这里你可以看到,search() 方法可以从字符串的任何位置查找一个模式。
广告