re模塊

import re

'''
\w匹配包括下劃線在內任何字母數字字符,它相當於類[a-zA-Z0-9]
\W匹配非任何字母數字字符包括下劃線在內,它相當於類[^a-zA-Z0-9
]
?P<>定義組裏匹配內容的key(鍵),<>裏面寫key名稱,值就是匹配到的內容
'''
#

str1 = "123 is 456"

str2 = re.sub("\d+", "5555", str1)

print(str2)

inputStr = "hello crifan, nihao crifan";
replacedStr = re.sub(r"hello (\w+), nihao \1", "crifanli", inputStr);
print(replacedStr)

inputStr = "hello crifan, nihao crifan";
replacedStr = re.sub(r"hello (\w+), nihao \1", "\g<1>", inputStr);
print(replacedStr)

其中\g<1>表示組1

inputStr5 = "hello victor is a good man";
replacedStr5 = re.sub(r"(.+?)", "w", inputStr5);
print("vitor is :", replacedStr5)

if re.search("ob", inputStr5):
print("find it!")

if re.match("hello", inputStr5):
print("matched!")

def pythonReSubDemo():
"""
demo Pyton re.sub
"""
inputStr = "hello 123 world 456";

def _add111(matched):
    intStr = matched.group("number"); #123
    intValue = int(intStr);
    addedValue = intValue + 111; #234
    addedValueStr = str(addedValue);
    return addedValueStr;

replacedStr = re.sub("(?P<number>\d+)", _add111, inputStr);
print(replacedStr) #hello 234 world 567

pythonReSubDemo();

str3 = " **abc is abc*****"
str4 = " "
print(str4.strip())
if str4.strip():
print("not null")
else:
print("str4 is null")
print(str3)
print(str3.strip())

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章