常見方法
!/usr/bin/python3
# -*- coding: utf-8 -*-
import re
string = '123abc123'
pattern = re.compile('\d+')
# result = pattern.match(string) # match 開頭匹配, 只匹配一次
# result = pattern.search(string) # search 全局匹配, 只匹配一次
# result = pattern.findall(string) # findall 返回是列表,列表中是所有的匹配結果
result = pattern.finditer(string) # finditer 返回是迭代對象,內部存放了匹配對象
for data in result:
print(data)
# print(result)
findall
把所有的結果匹配完成了才返回,數量小可以使用,但是數據量大不推薦使用
finditer
每匹配一個就返回一個,節省內存,適合數據量大的時候使用
re.compile()
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import re
string = '123abc'
string_list = ["123abc","123abc123"]
# print(re.findall('\d+',string))
# pattern = re.compile('\d+') #1. 編譯生成匹配規則
# print(pattern.findall(string)) # 2. 匹配數據
pattern = re.compile('\d+')
for string in string_list:
print(pattern.findall(string))
- re.findall ==> 1. 編譯生成匹配規則 2. 匹配數據
會創建上下文環境,吃性能和內存
- re.compile()創建匹配規則,可以重復利用
DOTALL模式
- re.DOTALL == re.S == re.RegexFlag.DOTALL == re.RegexFlag.S
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import re
string = '''
abcd
abcd
'''
pattern = re.compile('a(.*?)d') # 非貪婪 ['bc', 'bc']
pattern = re.compile('a(.*)d') # 貪婪 ['bc', 'bc']
pattern = re.compile('a(.*)d',re.RegexFlag.S) # DOTALL模式 ['bcd\n abc']
print(pattern.findall(string))
- (.*) 貪婪模式 -> 盡可能多的匹配
- (.*?) 非貪婪模式 -> 一旦匹配
- . 匹配的除'\n'以外所有字符,設置 DOTALL模式,讓 . 匹配包括 '\n' 所有字符
忽略大小寫
- re.IGNORECASE == re.I == re.RegexFlag.IGNORECASE == re.RegexFlag.I
# 多模式共同支持使用 |
pattern = re.compile('a(.*)d',re.DOTALL | re.IGNORECASE)
原始字符串
string = r"ab\ncd"
print(string) # "ab\ncd"
回退符\b
string = "abcd\b\bef"
print(string) # "abef"