python 正则表达质 re.sub() 的使用
生活随笔
收集整理的這篇文章主要介紹了
python 正则表达质 re.sub() 的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
re.sub() 函數的作用:
用于替換字符串中的匹配項
從源碼里面看下sub() 函數
里面五個參數pattern, repl, string 是必須要寫的? count, flags?是選填的
- pattern : 正則中的模式字符串。
- repl : 替換的字符串,也可為一個函數。
- string : 要被查找替換的原始字符串。
- count : 模式匹配后替換的最大次數,默認 0 表示替換所有的匹配。
- flags : 是標志位, 比如忽略匹配字母帶小寫,等.
2 下面寫2個demo 說下re.sub 的使用
2.1 sub里面的第二個參數repl 是字符串的情況
import re # 導入re 模塊# 把 123 替換成 tom
str_content = "hello 123 , are you ok?"
rex_content = re.sub("123", "tom", str_content)
print(rex_content)
# , 替換成空
str_content = "hello tom , are you ok?"
rex_content = re.sub(",", "", str_content)
print(rex_content)
打印結果如下:
?
2.2 sub里面的第二個參數repl 是函數的情況
import re # 導入re 模塊# 將匹配的數字乘于 2
def doubleNum(matched):value = int(matched.group('number'))return str(value * 2)if __name__ == "__main__":str_content = "hello 123 , are you ok?"rex_content = re.sub("(?P<number>\d+)", doubleNum, str_content)print(rex_content)
打印結果為:
前面我提示 group 的使用的,如果里面帶參數的看著不舒服可以修改一下 ,如下
import re # 導入re 模塊# 將匹配的數字乘于 2
def doubleNum(matched):value = int(matched.group())return str(value * 2)if __name__ == "__main__":str_content = "hello 123 , are you ok?"rex_content = re.sub("(\d+)", doubleNum, str_content)print(rex_content)
?
總結
以上是生活随笔為你收集整理的python 正则表达质 re.sub() 的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 向法院起诉要不要钱呢?要多少钱?
- 下一篇: 求一个谈恋爱的个性签名!