![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuEDM5ADN3UDNy0CN0EzMzAjM4ATOwkDM5EDMy0SO1YzNyMTMvwVOwkTMwIzLclTN2cjMzEzLcd2bsJ2Lc12bj5ycn9Gbi52YugTMwIzZtl2Lc9CX6MHc0RHaiojIsJye.png)
# 匹配变量名是否符合要求
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位英文字符数字下划线,例如[email protected]
import re
def main():
email = input("请输入邮箱前缀")
# email = "[email protected]"
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)
转载于:https://www.cnblogs.com/joycezhou/p/11489597.html