Python编程:re中findall()用法

        在re中,(re.findall(pattern, string, flags=0)):返回string中所有与pattern相匹配的全部字符串,得到数组。其用法大致分为四类,如下:

(1)r:查找string中出现r标识的字串

import re
text = "https://mp.csdn.net/postedit/82865219"
a = re.findall(r"pos", text)
#输出 
a = ['pos']

(2)^:匹配以^标识开头的字符串;$:匹配以$标识结束的字符串

import re
text1 = "https://mp.csdn.net  wwww "
text2 = "blog.csdn.net"
a1 = re.findall(r"^https", text1)
a2 = re.findall(r"^https", text2)
a3 = re.findall(r"$net", text1)
a4 = re.findall(r"$net", text2)
#输出 
a1 = ['https']
a2 = []
a3 = []
a4 = ['net']

(3)匹配括号中的其中一个字符

import re
text = "I am so happy! "
a1 = re.findall("[a-zA-Z]", text)
a2 = re.findall("[a-zA-Z]+", text)
 
#输出
a1 = ['I', 'a', 'm', 's', 'o', 'h', 'a', 'p', 'p', 'y']
a2 = ['I', 'am', 'so', 'happy']

(4)\d:匹配0到9之间的数字;\D:匹配除0到9之外的字符

import re
text = "https://mp.csdn.net/postedit/82865219"
a1 = re.findall("\d", text)
a2 = re.findall("\d\d", text)
a3 = re.findall("\D", text)
a4 = re.findall("\D+", text)
#输出 
a1 = ['8', '2', '8', '6', '5', '2', '1', '9']
a2 = ['82', '86', '52', '19']
a3 = ['h', 't', 't', 'p', 's', ':', '/', '/', 'm', 'p', '.', 'c', 's', 'd', 'n', '.', 'n', 'e', 't', '/', 'p', 'o', 's', 't', 'e', 'd', 'i', 't', '/']
a4 = : ['https://mp.csdn.net/postedit/']

你可能感兴趣的:(python)