1、查找所有:结果 = re.findall(正则, 字符串) => 返回列表,用法:r""专业写正则的。 没有转义的烦恼,result = re.findall(r"\d+", "我有1000万,不给你花,我有1块我给你")
2、结果 = re.finditer(正则, 字符串) => 返回迭代器(需要for循环),
result = re.finditer(r"\d+", "我有1000万,不给你花,我有1块我给你")
print(result) # iterator 循环拿结果
for it in result: # <re.Match object; span=(2, 6), match='1000'>
# print(it) # 从每一个Match里拿结果
print(it.group()) # group叫分组
# finditer =》迭代器 =》循环 => match => group()
3、# 结果 = re.search(正则,字符串), 全局搜索。 搜索到了。直接返回结果(返回第一个结果)
r = re.search(r"\d+", "我有1000万,不给你花,我有1块我给你")
print(r) # <re.Match object; span=(2, 6), match='1000'>
print(r.group())
4、多个相同格式的结果: finditer、单个格式的结果: search
5、加载好一个正则表达式用compile:obj = re.compile(r"\d+")
6、() 分组,?P<名字> 给这一组起名字,提取的时候就可以根据分组名字来提取具体数据,
s = """hahah<div class='西游记'><span id='10010'>中国联通</span></div><div class='三国杀'><span id='10086'>中国移动</span></div>heheh"""
obj = re.compile(r"<div class='(?P<jay>.*?)'><span id='(?P<id>.*?)'>(?P<lt>.*?)</span></div>")
result = obj.finditer(s)
for item in result:
print(item.group("jay"))
print(item.group("id"))
print(item.group("lt"))
7、常用元字符
. √匹配除换行符以外的任意字符, 未来在python的re模块中是一个坑.
\w √匹配字母或数字或下划线.
\s 匹配任意的空白符
\d √匹配数字
\n 匹配一个换行符
\t 匹配一个制表符
^ 匹配字符串的开始
$ 匹配字符串的结尾
\W 匹配非字母或数字或下划线
\D 匹配非数字
\S 匹配非空白符
a|b 匹配字符a或字符b
() √匹配括号内的表达式,也表示一个组
[...] √匹配字符组中的字符
[^...] 匹配除了字符组中字符的所有字符
8、量词: 控制前面的元字符出现的次数
* 重复零次或更多次
+ 重复一次或更多次
? 重复零次或一次
{n} 重复n次
{n,} 重复n次或更多次
{n,m} 重复n到m次
.* 贪婪匹配, 尽可能多的去匹配结果
.*? 惰性匹配, 尽可能少的去匹配结果 -> 回溯
9、