在Python中,正則表達式主要通過re模塊來實現。以下是一些常用的正則表達式用法:
匹配值:
pattern = r'\d+' # 匹配一個或多個數字
pattern = r'\b\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\b' #匹配日期格式
pattern = r'hello' # 匹配字符串“hello”
- \d 表示匹配一個數字字符,等價于 [0-9];
- +表示匹配前面的子表達式一次或多次
- \d{4}表示匹配四位數字
- \b 表示單詞邊界,確保匹配的時間字符串前后沒有其他數字或字符,在字符串首尾各一個
1、導入re模塊:
import re
2、使用re.search()函數查找字符串中是否包含指定的模式:
import re
pattern = r'\d+' # 匹配一個或多個數字
string = 'abc123def456'
result = re.search(pattern, string)
if result:print('找到匹配項:', result.group())
else:print('未找到匹配項')
3、使用re.findall()函數查找字符串中所有符合指定模式的子串
import re
pattern = r'\d+' # 匹配一個或多個數字
string = 'abc123def456'
result = re.findall(pattern, string)
print('找到的所有匹配項:', result)
4、使用re.sub()函數替換字符串中符合指定模式的子串:
import re
pattern = r'\d+' # 匹配一個或多個數字
replacement = 'NUM'
string = 'abc123def456'
result = re.sub(pattern, replacement, string)
print('替換后的字符串:', result)
5、使用re.split()函數根據指定模式分割字符串
import re
pattern = r'\d+' # 匹配一個或多個數字
string = 'abc123def456'
result = re.split(pattern, string)
print('分割后的字符串列表:', result)
6、使用re.compile()函數將正則表達式編譯為一個模式對象,以便重復使用:
import re
pattern = re.compile(r'\d+') # 匹配一個或多個數字
7、使用re.escape()函數對特殊字符進行轉義,以便在正則表達式中使用:
import re
string = 'a.b*c?d+e|f{g}h[i]j^k$l'
escaped_string = re.escape(string)
print('轉義后的字符串:', escaped_string)