python正则模块

来源:互联网 发布:java开发安卓应用 编辑:程序博客网 时间:2024/06/02 05:58

re.match() 总是从字符串“开头”去匹配,并返回匹配的字符串的match对象。所以当我用re.match()函数去匹配字符串非开头部分的字符串时,会返回NONE。

[python] view plain copy
  1. str1 = 'Hello World!'  
  2. print(re.match(r'e',str1))  
结果为:NONE

如果想查找字符串任意部分的模式出现位置请用re.search()或re.findall().


re.search()函数将对整个字符串进行搜索,并返回第一个匹配的字符串的match对象。

[python] view plain copy
  1. <pre name="code" class="python">str1 = 'Hello World!'  
print(re.search(r'e',str1))输出结果:

<_sre.SRE_Match object; span=(1, 2), match='e'>

re.findall()函数将返回一个所有匹配的字符串的字符串列表。

[python] view plain copy
  1. str1 = 'Hello World!'  
  2. re.findall(r'e',str1)  
输出结果将是:

['e']

如果你想以迭代方式返回匹配,可以使用 finditer() 方法来代替。



1.TypeError: cannot use a string pattern on a bytes-like object  这种情况解决方法就是加上html=html.decode('utf-8')#python3这句代码

原创粉丝点击