python之正則表達式 re.findall 用法


 

正則 re.findall 的簡單用法(返回string中所有與pattern相匹配的全部字串,返回形式為數組)
語法:findall(pattern, string, flags=0)

第一個參數,正則表達式

第二個參數,搜索的是那些字符串

第三個參數,匹配的模式,其中re.S使匹配包括換行在內的所有字符。findall()函數是逐行匹配的。

一、正則表達式的含義

 

 

懶惰匹配與貪婪匹配。

表達式 .* 的意思很好理解,就是單個字符匹配任意次,即貪婪匹配。
表達式 .*? 是滿足條件的情況只匹配一次,即懶惰匹配

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相匹配的全部字串,返回形式為數組

符號^表示匹配以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']
 
# [...]匹配括號中的其中一個字符
regular_v4 = re.findall(r"[t,w]h","https://docs.python.org/3/whatsnew/3.6.html")
print (regular_v4)   # ['th', 'wh']

  

“d”是正則語法規則用來匹配0到9之間的數返回列表
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', '/', '.',
'.', '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)
# [':', '/', '/', '.', '.', '/', '/', '/', '.', '.']

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM