Python正則表示式如何進行字串替換
阿新 • • 發佈:2018-12-30
Python正則表示式在使用中會經常應用到字串替換的程式碼。有很多人都不知道如何解決這個問題,下面的程式碼就告訴你其實這個問題無比的簡單,希望你有所收穫。
1.替換所有匹配的子串用newstring替換subject中所有與正則表示式regex匹配的子串
- result, number = re.subn(regex, newstring, subject)
2.替換所有匹配的子串(使 用正則表示式物件)
- rereobj = re.compile(regex)
- result, number = reobj.subn(newstring, subject)字串拆分
Python字串拆分
- reresult = re.split(regex, subject)
字串拆分(使用正則表示式物件)
- rereobj = re.compile(regex)
- result = reobj.split(subject)匹配
下面列出Python正則表示式的幾種匹配用法:
1.測試正則表示式是否 匹配字串的全部或部分regex=ur"..." #正則表示式
- if re.search(regex, subject):
- do_something()
else:do_anotherthing()2.測試正則表示式是否匹配整個字串regex=ur"...\Z" #正則表示式末尾以\Z結束
- if re.match(regex, subject):
- do_something()
- else:
- do_anotherthing()
3. 建立一個匹配物件,然後通過該物件獲得匹配細節regex=ur"..." #正則表示式
- match = re.search(regex, subject)
- if match:
- # match start: match.start()
- # match end (exclusive): match.end()
- # matched text: match.group()
- do_something()
- else:
- do_anotherthing()
以上就是對Python正則表示式在字串替換中的具體介紹。