函数说明
- result = re.match(正则表达式,要匹配的字符串):尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none
- result.group():用来提取匹配到的数据
- re.search():扫描整个字符串并返回第一个成功的匹配
运行如下代码
import re
result = re.match('hello', 'Hello135helloHELLO hehehellohell')
data = result.group()
print(data)
报错如下
Traceback (most recent call last):
File "C:\Users\pythonStudy\正则表达式.py", line 3, in <module>
data = result.group()
AttributeError: 'NoneType' object has no attribute 'group'
原因:match()函数只能从头起始位置匹配,不能匹配中间内容
修改如下
方式一:将要匹配的字符串放在字符串开头,运行正常
import re
result = re.match('hello', 'helloHELLO hehehellohell')
data = result.group()
print(data)
输出:
hello
方式二:使用search()函数替换match(),运行正常
import re
result = re.search('hello', 'Hello135helloHELLO hehehellohell')
data = result.group()
print(data)
输出:
hello
学习导航:http://xqnav.top/