re.sub参数之回调函数

from calendar import month_abbr
import re


def change_date(m):
    mon_name = month_abbr[int(m.group(1))]
    return '{} {} {}'.format(m.group(2), mon_name, m.group(3))


if __name__ == '__main__':
    text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
    datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
    # 先会执行匹配,然后将匹配到的match对象传入到回调函数中
    print(datepat.sub(change_date, text))


def matchcase(word): 
    def replace(m): 
        text = m.group() 
        if text.isupper(): 
            return word.upper() 
        elif text.islower(): 
            return word.lower() 
        elif text[0].isupper(): 
            return word.capitalize() 
        else: 
            return word 
    return replace
if __name__ == '__main__':
  re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE)
posted @ 2023-07-10 08:47  我在路上回头看  阅读(14)  评论(0编辑  收藏  举报