在 Python 中搜索和替換
使用正則表示式的最重要重寫方法之一是sub。
語法
re.sub(pattern, repl, string, max=0)
此方法會將所有 RE string 中的 pattern 替換為 repl ,除非提供了 max,否則會替換所有出現的例項。此方法會返回修改後的字串。
示例
#!/usr/bin/python import re phone = "2004-959-559 # This is Phone Number" # Delete Python-style comments num = re.sub(r'#.*$', "", phone) print "Phone Num : ", num # Remove anything other than digits num = re.sub(r'\D', "", phone) print "Phone Num : ", num
輸出
在執行以上程式碼時,會產生以下結果:
Phone Num : 2004-959-559 Phone Num : 2004959559
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP