1. findall()
re.findall()在字符串中找到正則表達式所匹配的所有子串,並返回一個列表;如果沒有找到匹配的,則返回空列表。
返回結果是列表類型,需要遍歷一下才能依次獲取每組內容。
findall(patern, string, flags=0)
- pattern : 正則中的模式字符串。
- string : 要被查找替換的原始字符串。
- flags : 標誌位,用於控制正則表達式的匹配方式,如:是否區分大小寫,多行匹配等等。
- 例子:
import re
content = 'Hello 123456789 Word_This is just a test 666 Test'
results = re.findall('\d+', content)
print(results)
for result in results:
print(result)
- 結果:
['123456789', '666']
123456789
666
Process finished with exit code 0
注意利用re.findall()函數沒有group()和groups(),因爲其返回結果是一個列表。
2. re.compile()方法
re.compile()方法可以將正則字符串編譯成正則表達式對象,以便在後面的匹配中複用。
re.compile(pattern[, flags])
re.compile()中可以傳入忽略換行等匹配模式,這樣在search()、findall()方法中就不需要額外傳入了。
因此,re.findall()方法有2種表達方式:
- 例子:
import re
content = 'one1two22three333four4444'
pattern = re.compile(r'\d+')
print('===方法1:===')
result1 = re.findall(pattern, content)
print(result1)
print('===方法2===')
result2 = pattern.findall(content)
print(result2)
- 結果:
===方法1:===
['1', '22', '333', '4444']
===方法2===
['1', '22', '333', '4444']
Process finished with exit code 0
3. 注意事項
在使用findall()方法時的“坑”:注意正則表達式中括號()的使用
(1)正則表達式中沒有括號時,正常匹配:
import re
str1 = '2345 3456 4567 5678 6789'
pattern_1 = re.compile('\w+\s+\w+') # \w 表示匹配包括下劃線的任何單詞字符,等價於[A-Za-z0-9_]
print(pattern_1.findall(str1))
結果:
['2345 3456', '4567 5678']
Process finished with exit code 0
(2)正則表達式中有一個括號時,其輸出的內容就是括號匹配到的內容,而不是整個表達式所匹配到的結果:
import re
str1 = '2345 3456 4567 5678 6789'
pattern_1 = re.compile('(\w+)\s+\w+') # \w 表示匹配包括下劃線的任何單詞字符,等價於[A-Za-z0-9_]
print(pattern_1.findall(str1))
結果:
['2345', '4567']
Process finished with exit code 0
整個正則表達式執行了,只不過只輸出括號匹配到的內容,即輸出的是第一個 (\w+) 匹配到的內容:
在第一次匹配時跟上述沒有括號時一樣,匹配到"2345 3456",只不過只輸出(/w+)匹配到的結果 即"2345";
第二次匹配同理,從"4567" 開始,匹配到"4567 5678",但是還是隻是輸出(/w+)匹配到的結果 即"4567"。
(3)當正則表達式中有兩個括號時,其輸出是一個list 中包含2個 tuple:
import re
str1 = '2345 3456 4567 5678 6789'
pattern_1 = re.compile('((\w+)\s+\w+)') # \w 表示匹配包括下劃線的任何單詞字符,等價於[A-Za-z0-9_]
print(pattern_1.findall(str1))
# 結果:
[('2345 3456', '2345'), ('4567 5678', '4567')]
Process finished with exit code 0
從輸出的結果可以看出,結果中包含兩個元組,每一個元組中有兩個字符串。
第一個元組是第一次匹配的結果,其中的第一個字符串 "2345 3456" 是正則表達式最外面的括號
((\w+)\s+\w+)
匹配輸出的結果;
第一個元組中的第二個字符串 "2345"是正則表達式裏面括號
(\w+)
匹配輸出的結果 ;
第二個元組是第二次匹配的結果,匹配原理與第一次匹配相同。
參考:
https://blog.csdn.net/YZXnuaa/article/details/79346963
https://blog.csdn.net/zd147896325/article/details/79010621
https://www.cnblogs.com/one-lightyear/p/6814833.html