元字符
. 除了换行符以外的任意一个字符
\w 匹配数字字母下划线
\s 匹配空白符
\d 匹配数字
\n 匹配换行符
\t 制表符
^ 匹配字符串的开始
$ 匹配字符串的结束
\W 匹配非字母或数字或下划线
\D 非数字
\S 非空白
a|b 匹配字符a或者b
() 匹配括号的表达式
[...] 匹配字符组中的字符 => [a-zA-Z0-9] [abcde]
[^...] 匹配除了字符组中的所有字符
量词
* 重复0或者多次
+ 重复1次或者多次
\d+ 数字至少出现1次
? 重复0次或者1次
{n} 重复n次
\d{5} 数字出现5次
{n,} 重复n次或者更多次
{n,m} 重复n到m次
贪婪匹配,惰性匹配
.*:
尽可能多的去匹配
.*?:
尽可能少的匹配
其他
re.S 让.能匹配换行符
?P<匹配标识变量名>
re模块
- findall 返回列表,匹配所有符合的内容
- finditer,匹配所有符合内容,返回迭代器
·
it = re . finditer(ex, str)
for i in it:
print(it.group())
- search:返回match对象,检索到一个就返回
- match:从字符串头部开始匹配
- 预加载正则
··
obj = re.compile(正则expression)
obj.method;(上述方法)
import re
s = """
<div class='jay1'><span id='1'>kk1</span></div>
<div class='jay2'><span id='2'>kk2</span></div>
<div class='jay3'><span id='3'>kk3</span></div>
"""
obj = re.compile(r"<div class='(?P<class>.*?)'><span id='(\d+)'>(.*?)</span></div>", re.S)
res = obj.finditer(s)
for it in res:
print(it.group("class"))
jay1
jay2
jay3