Python正则表达式re.sub使用
生活随笔
收集整理的這篇文章主要介紹了
Python正则表达式re.sub使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、引入正則表達式
import re2、使用re.sub進行字符串替換
re.sub(pattern, repl, string, count=0, flags=0) 其中三個必選參數:pattern, repl, string兩個可選參數:count, flags比如\6,表示匹配前面pattern中的第6個group,意味著,pattern中,前面肯定是存在對應的,第6個group,然后你后面也才能去引用;
練習1
import re inputStr = "hello crifan, nihao crifan, nihao ccc " match_str=re.match(r"hello (\w+)",inputStr) #\w匹配字母、數字、下劃線 print(match_str.group(0)) print(match_str.group(1)) replacedStr = re.sub(r"hello (\w+), nihao \1", "crifanli", inputStr) print(replacedStr)運行結果:
hello crifan
crifan
hello crifan, nihao crifan, nihao ccc
練習2:提取輸入字符串中的數字
import re option=input("") option_str=re.sub("\D","",option) #\D匹配非數字字符 print(option_str)運行結果:
生活1生活2
12
總結
以上是生活随笔為你收集整理的Python正则表达式re.sub使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: delphi if多个条件_判断(if)
- 下一篇: 机器学习-01regression