# 匹配變量名是否符合要求 import re def main(): names = ["name1", "_name", "2_name", "__name__", "___", "name!"] for name in names: ret = re.match("^[a-zA-Z_][a-zA-Z0-9]*$", name) if ret: print("變量名%s %s 符合要求" % (name, ret.group())) else: print("變量名 %s 不符合要求" % name) if __name__ == "__main__": main()
# 匹配163的郵箱地址,且@字符以前4到20位英文字符數字下劃線,例如hello@163.com import re def main(): email = input("請輸入郵箱前綴") # email = "zhou@163.com" ret = re.match(r"^[a-zA-Z0-9]{4,20}@163\.com$", email) if ret: print("輸入合法%s" % ret.group()) else: print("%s 不合法" % email) if __name__ == "__main__": main()
import re# search 第一個ret = re.search(r"\d+", "閱讀次數爲 9999, 點贊數爲:100")print(ret.group())# findall 全部的ret = re.findall(r"\d+", "閱讀次數爲 9999, 點贊數爲:100")print(ret)# sub全部的替換ret = re.sub(r"\d+", "9998", "閱讀次數爲 9999, 點贊數爲:100")print(ret)# split 切割字符串,返回一個列表ret = re.split(r":| ", "閱讀次數爲:9999, 點贊數爲:100")print(ret)