一、re模块示例(匹配以itcast开头的语句)
- re.match() 能够匹配出以xxx开头的字符串
#coding=utf-8
import re
result = re.match("hello","hello world")
result.group()
运行结果为:
hello
匹配开头结尾
字符 | 功能 |
---|---|
^ | 匹配字符串开头 |
$ | 匹配字符串结尾 |
python贪婪和非贪婪
Python里数量词默认是贪婪的(在少数语言里也可能是默认非贪婪),总是尝试匹配尽可能多的字符;
非贪婪则相反,总是尝试匹配尽可能少的字符。
在"*","?","+","{m,n}"后面加上?,使贪婪变成非贪婪。
re模块的高级用法
一、search(全盘搜索,找到就返回,返回的是match)
import re
ret = re.search(r"\d+", "阅读次数为 9999")
ret.group()
运行结果:
'9999'
二、findall(全盘搜索,找到所有再返回,返回的是一个列表)
import re
ret = re.findall(r"\d+", "python = 9999, c = 7890, c++ = 12345")
print(ret)
运行结果:
['9999', '7890', '12345']
四、sub 将匹配到的数据进行替换(全盘搜索,找到替换,返回的是一个字符串)
需求:将匹配到的阅读次数加1
方法1:
#coding=utf-8
import re
ret = re.sub(r"\d+", '998', "python = 997")
print(ret)
运行结果:
python = 998
方法2:
#coding=utf-8
import re
def add(temp):
strNum = temp.group()
num = int(strNum) + 1
return str(num)
ret = re.sub(r"\d+", add, "python = 997")
print(ret)
ret = re.sub(r"\d+", add, "python = 99")
print(ret)
运行结果:
python = 998
python = 100
五、split 根据匹配进行切割字符串,并返回一个列表(全盘搜索)
import re
ret = re.split(r":| ","info:xiaoZhang 33 shandong")
print(ret)
运行结果:
['info', 'xiaoZhang', '33', 'shandong']