python之正则表达式 re.findall 用法

1
  
findall(pattern, string, flags
=
0
)

第一个参数,正则表达式

第二个参数,搜索的是那些字符串

第三个参数,匹配的模式,其中re.S使匹配包括换行在内的所有字符。findall()函数是逐行匹配的。

一、正则表达式的含义

 

 

懒惰匹配与贪婪匹配。

表达式 .* 的意思很好理解,就是单个字符匹配任意次,即贪婪匹配。
表达式 .*? 是满足条件的情况只匹配一次,即懒惰匹配

1
2
3
4
5
6
7
8
9
10
11
var str = 'Anna is {age} years old,Bob is {age} years old too';
var expr = /{.*?}/g;
console.log(str.replace(expr, '13'));
命令行输出: Anna is 13 years old,Bob is 13 years old too
 
可以看出,懒惰模式下,只要满足条件,就不再向后匹配,以下是贪婪模式:
 
var str = 'Anna is {age} years old,Bob is {age} years old too';
var expr = /{.*}/g;
console.log(str.replace(expr, '13'));
命令行输出: Anna is 13 years old too

  


返回string中所有与pattern相匹配的全部字串,返回形式为数组

1
2
3
4
5
6
7
8
符号^表示匹配以https开头的的字符串返回,
regular_v2 = re.findall(r"^https","https://docs.python.org/3/whatsnew/3.6.html")
print (regular_v2)  # ['https']
 
用$符号表示以html结尾的字符串返回,判断是否字符串结束的字符串
 
regular_v3 = re.findall(r"html$","https://docs.python.org/3/whatsnew/3.6.html")
print (regular_v3)   # ['html']
 
1
2
3
# [...]匹配括号中的其中一个字符
regular_v4 = re.findall(r"[t,w]h","https://docs.python.org/3/whatsnew/3.6.html")
print (regular_v4)   # ['th', 'wh']

  

1
2
3
4
5
6
7
8
9
10
“d”是正则语法规则用来匹配09之间的数返回列表
regular_v5 = re.findall(r"\d","https://docs.python.org/3/whatsnew/3.6.html")
regular_v6 = re.findall(r"\d\d\d","https://docs.python.org/3/whatsnew/3.6.html/1234")
print (regular_v5)   # ['3', '3', '6']
print (regular_v6)   # ['123']
 
小d表示取数字0-9,大D表示不要数字,也就是出了数字以外的内容返回
regular_v7 = re.findall(r"\D","https://docs.python.org/3/whatsnew/3.6.html")
print (regular_v7)
# ['h', 't', 't', 'p', 's', ':', '/', '/', 'd', 'o', 'c', 's', '.', 'p', 'y', 't', 'h', 'o', 'n', '.', 'o', 'r', 'g', '/', '/', 'w', 'h', 'a', 't', 's', 'n', 'e', 'w', '/', '.',<br> '.', 'h', 't', 'm', 'l']

  

复制代码
“w”在正则里面代表匹配从小写a到z,大写A到Z,数字0到9
regular_v8 = re.findall(r"\w","https://docs.python.org/3/whatsnew/3.6.html")
print (regular_v8)
#['h', 't', 't', 'p', 's', 'd', 'o', 'c', 's', 'p', 'y', 't', 'h', 'o', 'n', 'o', 'r', 'g', '3', 'w', 'h', 'a', 't', 's', 'n', 'e', 'w', '3', '6', 'h', 't', 'm', 'l']


“W”在正则里面代表匹配除了字母与数字以外的特殊符号
regular_v9 = re.findall(r"\W","https://docs.python.org/3/whatsnew/3.6.html")
print (regular_v9)
# [':', '/', '/', '.', '.', '/', '/', '/', '.', '.']
复制代码

 

 
posted @   木棉花的漂泊  阅读(3511)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示