1. 程式人生 > >python 正則表示式匹配

python 正則表示式匹配

import re


def match_case(word):
    def replace(m):
        text_group = m.group()
        if text_group.isupper():
            return word.upper()
        elif text_group.islower():
            return word.lower()
        elif text_group[0].isupper():
            return word.capitalize()
        else
: return word return replace if __name__ == '__main__': text = 'UPPER PYTHON, lower python, Mixed Python' test_upper = re.findall("python", text, flags=re.IGNORECASE) # print(test_upper) test_upper_1 = re.sub("python", "test", text, flags=re.IGNORECASE) # print(test_upper_1)
test_upper_2 = re.sub("python", match_case("test"), text, flags=re.IGNORECASE) print(test_upper_2)

兩種函式的巢狀使用