1. 程式人生 > >Python正則表示式如何進行字串替換

Python正則表示式如何進行字串替換

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

1.替換所有匹配的子串用newstring替換subject中所有與正則表示式regex匹配的子串

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

2.替換所有匹配的子串(使 用正則表示式物件)

  1. rereobj = re.compile(regex)  
  2. result, number = reobj.subn(newstring, subject)字串拆分 

Python字串拆分

  1. reresult = re.split(regex, subject) 

字串拆分(使用正則表示式物件)

  1. rereobj = re.compile(regex)  
  2. result = reobj.split(subject)匹配 

下面列出Python正則表示式的幾種匹配用法:

1.測試正則表示式是否 匹配字串的全部或部分regex=ur"..." #正則表示式

  1. if re.search(regex, subject):  
  2. do_something() 

else:do_anotherthing()2.測試正則表示式是否匹配整個字串regex=ur"...\Z" #正則表示式末尾以\Z結束

  1. if re.match(regex, subject):  
  2. do_something()  
  3. else:  
  4. do_anotherthing() 

3. 建立一個匹配物件,然後通過該物件獲得匹配細節regex=ur"..." #正則表示式

  1. match = re.search(regex, subject)  
  2. if match:  
  3. # match start: match.start()  
  4. # match end (exclusive): match.end()  
  5. # matched text: match.group()  
  6. do_something()  
  7. else:  
  8. do_anotherthing() 

以上就是對Python正則表示式在字串替換中的具體介紹。