Python正则表达式解释
小编写这篇文章的主要目的,主要是给大家做出一个解答,主要是用来解答Python正则表达式的内容,包括re.compile()和re.findall(),两种常见类型代码的解释,关于这两方面的内容,下面给大家详细的做个介绍。

re.compile()和re.findall()
在使用爬虫提取网页中的部分信息时,采用到了re.compile()与re.findall()两种方法,目的:把网页中的“某某城市土地规划表”截取并打印出来。
以下是针对这种情况的详细介绍,供大家学习参考:
<span class='tab-details'>某某城市土地规划表</span>
def parse_response(html):
pattern = re.compile('class=\'tab-details\'>(.*?)</span>', re.S)
items = re.findall(pattern, html)
print(items)
return items
结果:
['某某城市土地规划表']
pattern、re.compile()和re.findall()的定义及用法
在这里,我们主要讲解pattern,re.compile()与re.findall()的定义及用法:
- pattern:pattern属性规定用于验证输入字段的正则表达式。
- re.compile():compile()方法用于在脚本执行过程中编译正则表达式,也可用于改变和重新编译正则表达式。
- re.findall():re.findall()函数是返回某种形式(比如String)中所有与pattern匹配的全部字符串,返回形式为数组。
举例:在字符串中全局搜索”man”,并用”person”替换。然后通过compile()方法,改变正则表达式,用”person”替换”man”或”woman”:
<script type="text/javascript">
var str="Every man in the world! Every woman on earth!";
patt=/man/g;
str2=str.replace(patt,"person");//用person取代man
document.write(str2+"<br/>");
patt=/(wo)?man/g;
patt.compile(patt);
str2=str.replace(patt,"person");//用person取代man或者woman
document.write(str2);
</script>
输出:
Every person in the world! Every person on earth!
Every person in the world! Every person on earth!
常用的正则表达式
下面是一些常用的正则表达式:
var str = "aabbabaabbaa";
//一个"."就是匹配除"\n"(换行符)以外的任意一个字符
console.log(re.findall('a.b', str));//['aab','aab']
//"*"前面的字符出现0次或以上
console.log(re.findall('a*b', str));//['aab', 'b', 'ab', 'aab', 'b']
//贪婪,匹配从"."前面为开始到后面为结束的所有内容
console.log(re.findall('a.*b', str));//['aabbabaabb']
//非贪婪,遇到开始和结束就进行截取,因此截取多次符合的结果,中间没有字符也会被截取
console.log(re.findall('a.*?b', str));//['aab', 'ab', 'aab']
//非贪婪,与上面一样,只是与上面的相比多了一个括号,只保留括号的内容
console.log(re.findall('a(.*?)b', str));//['a', '', 'a']
var str = 'aabbab\naabbaabb';
//没有把最后一个换行的aab算进来
console.log(re.findall('a.*?b', str));//['aab', 'ab', 'aab']
//re.S不会对\n进行中断
console.log(re.findall('a.*?b', str, re.S));//['aab', 'ab', 'aab', 'aa\n\tb']
注意’.*?’是对它的前后部分作为开始结束部分进行截取,而'(.*?)’也是把其前后作为开始结束,但是只截取括号部分,不包含开始结束部分!
原创文章,作者:小编小本本,如若转载,请注明出处:https://www.benjiyun.com/yunzhujiyunwei/vps-yunwei/7248.html
