Python用Regex進行字串替換方法

來源:互聯網
上載者:User
PythonRegex在使用中會經常應用到字串替換的代碼。這篇文章主要介紹了PythonRegex如何進行字串替換,具有一定的參考價值,感興趣的小夥伴們可以參考一下。

PythonRegex在使用中會經常應用到字串替換的代碼。有很多人都不知道如何解決這個問題,下面的代碼就告訴你其實這個問題無比的簡單,希望你有所收穫。

1.替換所有匹配的子串用newstring替換subject中所有與Regexregex匹配的子串

result, number = re.subn(regex, newstring, subject)

2.替換所有匹配的子串(使 用Regex對象)

rereobj = re.compile(regex) result, number = reobj.subn(newstring, subject)

Python字串拆分

reresult = re.split(regex, subject)

字串拆分(使用正則表示式對象)

rereobj = re.compile(regex) result = reobj.split(subject)

下面列出PythonRegex的幾種匹配用法:

1.測試Regex是否 匹配字串的全部或部分regex=ur"..." #Regex

if re.search(regex, subject): do_something() else:do_anotherthing()

2.測試Regex是否匹配整個字串regex=ur"...\Z" #Regex末尾以\Z結束

if re.match(regex, subject): do_something() else: do_anotherthing()

3. 建立一個匹配對象,然後通過該對象獲得匹配細節regex=ur"..." #Regex

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()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.