Python正则表达式的一些基本例子

Python正则表达式的一些基本例子

这里有两个Python正则表达式的基本例子

re.match()方法可以在字符串开头找到匹配的结果。例如,在字符串“TP Tutorials Point TP”上调用match()方法并查找模式“TP”会发现匹配结果。但是,如果我们只查找“Tutorials”,模式将无法匹配。让我们看看代码。

更多Python相关文章,请阅读:Python 教程

示例

import re result = re.match(r'TP', 'TP Tutorials Point TP')
print result

输出

<_sre.SRE_Match object at 0x0000000005478648>

re.search()方法与re.match()方法相似,但它不仅限制我们查找字符串开头的匹配结果。不像re.match()方法,这里在字符串“TP Tutorials Point TP”中查找模式“Tutorials”将会返回匹配结果。

示例

import re
result = re.search(r'Tutorials', 'TP Tutorials Point TP')
print result.group()

输出

Tutorials

这里可以看到,search()方法能够从任意位置的字符串中找到模式,但它只返回搜索模式的第一个匹配结果。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程