python筆記54-re正則匹配替換字符串(sub和subn)


前言

python 里面可以用 replace 實現簡單的替換字符串操作,如果要實現復雜一點的替換字符串操作,需用到正則表達式。
re.sub用於替換字符串中匹配項,返回一個替換后的字符串,subn方法與sub()相同, 但返回一個元組, 其中包含新字符串和替換次數。

sub介紹

Python 的 re 模塊提供了re.sub用於替換字符串中的匹配項,sub是substitute表示替換。

  • pattern:該參數表示正則中的模式字符串;
  • repl:repl可以是字符串,也可以是可調用的函數對象;如果是字符串,則處理其中的反斜杠轉義。如果它是可調用的函數對象,則傳遞match對象,並且必須返回要使用的替換字符串
  • string:該參數表示要被處理(查找替換)的原始字符串;
  • count:可選參數,表示是要替換的最大次數,而且必須是非負整數,該參數默認為0,即所有的匹配都會被替換;
  • flags:可選參數,表示編譯時用的匹配模式(如忽略大小寫、多行模式等),數字形式,默認為0。
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)

sub使用示例

將字符串中的數字替換成*號

import re
'''
替換字符串中的數字為*號
'''
s = '作者-上海悠悠 QQ交流群:717225969 blog地址:https://www.cnblogs.com/yoyoketang/ 歡迎收藏'

new = re.sub("[0-9]", "*", s)
print(new)
# 作者-上海悠悠 QQ交流群:********* blog地址:https://www.cnblogs.com/yoyoketang/ 歡迎收藏

把字符串 s 中的每個空格替換成"%20"

import re
'''
替換s中的空格為%20
'''
s = "We are happy."
print(re.sub(r' ', "%20", s))

# We%20are%20happy.

把字符串中的連續數字替換成hello

import re
'''
把字符串中的連續數字替換成hello
'''
s = "the number 200-40-3000"
print(re.sub(r'[\d]+', "hello", s))

# the number hello-hello-hello

替換時間格式 01/11/2021 替換成 2021/01/11

import re
'''
替換時間格式 01/11/2021 替換成 2021/01/11
'''

s = "today is 01-11-2021."
day = re.sub(r'(\d{2})-(\d{2})-(\d{4})', r'\3-\2-\1', s)
print(day) # today is 2021-11-01.

# 也可以用g<3>-g<2>-g<1>
day2 = re.sub(r'(\d{2})-(\d{2})-(\d{4})', r'g<3>-g<2>-g<1>', s)
print(day) # today is 2021-11-01.

\3\g<3>指代的的都是前面匹配的第3個分組

repl傳函數對象

匹配字符串中的數字加2

import re
'''
匹配字符串中的數字加2
'''

def addAge(match) ->str:
    '''返回匹配的值加2'''
    age = match.group()
    return str(int(age)+2)

s = 'my age is 20'
# repl 如果它是可調用的函數對象,則傳遞match對象,並且必須返回要使用的替換字符串
x = re.sub(r'[\d]+', addAge, s)
print(x)
# my age is 22

count替換次數

sub 加 count 參數可以控制要替換的最大次數,而且必須是非負整數,該參數默認為0,即所有的匹配都會被替換;

import re

'''
替換字符串中的空格為%20,只替換一次
'''
s = "We are happy."
print(re.sub(" ", "%20", s, count=1))

# We%20are happy.

subn方法使用

subn方法與sub()相同, 但返回一個元組, 其中包含新字符串和替換次數。

import re

'''
替換字符串中的空格為%20,只替換一次
'''
s = "We are happy."
x, n = re.subn(" ", "%20", s, )
print("替換后:", x)
print("替換次數: ", n)

運行結果
替換后: We%20are%20happy.
替換次數: 2


免責聲明!

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



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