Python---re.findall的用法
阿新 • • 發佈:2018-12-16
re.findall的用法
在import re中,(re.findall(pattern, string, flags=0)):返回string中所有與pattern相匹配的全部字串,得到陣列
r:查詢string中出現r標識的字串
>>>import re
>>>text = "https://mp.csdn.net/postedit/82865219"
>>>array = re.findall(r"pos", text)
['pos']
^:匹配以^標識開頭的字串 $:匹配以$標識結束的字串
>>>import re >>>text1 = "https://mp.csdn.net wwww " >>>text2 = "blog.csdn.net" >>>array1 = re.findall(r"^https", text1) array2 = re.findall(r"^https", text2) array3 = re.findall(r"$net", text1) array4 = re.findall(r"$net", text2) array1 = ['https'] array2 = [] array3 = [] array4 = ['net']
[]:匹配括號中的其中一個字元
>>>import re
>>>text = "I am so happy! "
>>>array1 = re.findall("[a-zA-Z]", text)
array2 = re.findall("[a-zA-Z]+", text)
array1 = ['I', 'a', 'm', 's', 'o', 'h', 'a', 'p', 'p', 'y']
array2 = ['I', 'am', 'so', 'happy']
\d:匹配0到9之間的數字 \D:匹配除0到9之外的字元
>>>import re >>>text = "https://mp.csdn.net/postedit/82865219" >>>array1 = re.findall("\d", text) array2 = re.findall("\d\d", text) array3 = re.findall("\D", text) array4 = re.findall("\D+", text) array1 = ['8', '2', '8', '6', '5', '2', '1', '9'] array2 = ['82', '86', '52', '19'] array3 = ['h', 't', 't', 'p', 's', ':', '/', '/', 'm', 'p', '.', 'c', 's', 'd', 'n', '.', 'n', 'e', 't', '/', 'p', 'o', 's', 't', 'e', 'd', 'i', 't', '/'] array4 = <class 'list'>: ['https://mp.csdn.net/postedit/']