python re.sub的使用


python re.sub 使用起來很方便,寫 python 代碼常常都會用到。了解它的用法是很有必要的。

源代碼中定義如下:

def sub(pattern, repl,string, count=0, flags=0):
    """Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the match object and must return
    a replacement string to be used."""
    return _compile(pattern, flags).sub(repl,string, count)
  • pattern,可以是一個字符串也可以是一個正則表達式,用於匹配要替換的字符,如果不寫,字符串不做修改。
  • repl,表示要替換的字符串(即匹配到pattern后替換為repl),也可以是個函數。

    • 如果是一個字符串,反斜杠會被處理為轉義字符。\g<1> 代表前面pattern里面第一個分組,可以簡寫為\1\g<0>代表前面pattern匹配到的所有字符串

    • repl如果是一個function,每一個被匹配到的字段串執行替換函數。if it is a callable, it's passed the match object and must return a replacement string to be used

  • string,表示要被處理(查找替換)的原始字符串;
  • count,是pattern被替換的最大次數,默認是0會替換所有。有時候可能只想替換一部分,可以用到count
  • flags,匹配模式

示例 1:

import re

a = re.sub(r'hello','i love you','hello world')
print(a)

執行結果:

i love you world

示例 2:

import re

a = re.sub(r'(\d+)','100','www.baidu.com is 3 yeas old!')
print(a) 

執行結果:

www.baidu.com is 100 yeas old! 

示例 3:

import re

a = re.sub(r'(\d+).*','\g<1> good tutorial website!','www.baidu.com is 3 yeas old!')
print(a)

執行結果:

www.baidu.com is 3 good tutorial website! 

示例 4:

import re

str1 ='<ol start="4" data-tool="mdnice編輯器" style="margin-top: 8px;margin-bottom: 8px;padding-left: 25px;color: black;" class="list-paddingleft-2">'
str2 ='<ol data-tool="mdnice編輯器" style="margin-top: 8px;margin-bottom: 8px;padding-left: 25px;color: black;" class="list-paddingleft-2">'

a = re.sub(r'<ol .*?(start=".*?"){0,1}.*?>','<ol \g<1>>', str1)
print(a)
b = re.sub(r'<ol .*?(start=".*?"){0,1}.*?>','<ol \g<1>>', str2)
print(b) 

執行結果:

<ol start="4">
<ol >  

示例 5:

import re
def replace_num(str):
    numDict ={'0':'〇','1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七','8':'八','9':'九'}
    print(str.group(0))
    return numDict[str.group(0)]
my_str ='2021年11月01號'
a = re.sub(r'(\d)', replace_num, my_str)
print(a)#每次匹配一個數字,執行函數,獲取替換后的值 

執行結果:

2
0
2
1
1
1
0
1
二〇二一年一一月〇一號

=========================================

import re
def replace_num(str):
    numDict ={'0':'〇','1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七','8':'八','9':'九'}
    print(str.groups())
    return numDict[str.group(0)]
my_str ='2021年11月01號'
a = re.sub(r'(\d)', replace_num, my_str)
print(a)#每次匹配一個數字,執行函數,獲取替換后的值 

執行結果:

('2',)
('0',)
('2',)
('1',)
('1',)
('1',)
('0',)
('1',)
二〇二一年一一月〇一號

 ============================================

import re
def replace_num(str):
    numDict ={'0':'〇','1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七','8':'八','9':'九'}
    print(str)
    return numDict[str.group(0)]
my_str ='2021年11月01號'
a = re.sub(r'(\d)', replace_num, my_str)
print(a)#每次匹配一個數字,執行函數,獲取替換后的值 

執行結果:

<re.Match object; span=(0, 1), match='2'>
<re.Match object; span=(1, 2), match='0'>
<re.Match object; span=(2, 3), match='2'>
<re.Match object; span=(3, 4), match='1'>
<re.Match object; span=(5, 6), match='1'>
<re.Match object; span=(6, 7), match='1'>
<re.Match object; span=(8, 9), match='0'>
<re.Match object; span=(9, 10), match='1'>
二〇二一年一一月〇一號

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM