# 匹配变量名是否符合要求 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)