需求
有时我们需要在一端文本中提取出我们想要的字符串,常用的场景:在一段网页源代码中提取某一个的标签中的数据
例子
1、例如,我们想要获取<div id="content"></div>中的数据
<html>
<head>
...
</head>
<body>
...
<div id="content">
想要获取的数据
</div>
<body>
</html>
2、利用re.compile().finall()获取
content = '<html>
<head>
...
</head>
<body>
...
<div id="content">
想要获取的数据
</div>
<body>
</html>'
re.compile('<div id="content">(.*)</div>').finall(content)
3、使用解读
compile()方法传的是正则表达式,findall()方法传的是要匹配的文本,.*代表匹配多个任意字符,加上()是为了返回括号中的字符串