python知识捡拾---正则相关

本文深入探讨了正则表达式的应用,通过多个实例详细解析了如何使用正则表达式进行字符串匹配,包括数字、字母、邮箱、网页元素等常见场景,是正则表达式学习与实践的实用参考资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

正则

re
  • ret = re.match(r"速度与激情\d",“速度与激情91”)

  • ret.group() ----> ‘速度与激情9’

  • re.match(r"速度与激情[1-8]",“速度与激情9”)

  • re.match(r"速度与激情[1-36-8]",“速度与激情2”).group()

  • re.match(r"速度与激情[\d\w]",“速度与激情ab”).group()

  • re.match(r"速度与激情[\d\w]",“速度与激情5”).group()

  • re.match(r"速度与激情.",“速度与激情!”).group() ‘速度与激情!’

  • re.match(r’速度与激情\d{1,2}’,“速度与激情12”).group() ‘速度与激情12’

  • re.match(r’速度与激情\d{1,2}’,“速度与激情123”).group() ‘速度与激情12’

  • re.match(r"021-\d{8}",“021-12345678”).group() Out[8]: ‘021-12345678’

  • re.match(r"021-?\d{8}",“02112345678”).group() Out[9]: ‘02112345678’

  • html_content=""“fdsfs
    fjskldfjalsd
    jflasdjfasdfk
    kflashdlg;ajsl
    fdfs”""

  • re.match(r".*",html_content).group() Out[11]: 'fdsfs’这里.*匹配除换行之外的任意字符

  • re.match(r".*",html_content,re.S).group() re.S可以匹配所有 输出:‘fdsfs\nfjskldfjalsd\njflasdjfasdfk\nkflashdlg;ajsl\nfdfs’

  • re.match(r"[a-zA-Z0-9_]{4,20}@(163|126).com$",“laowang@126.com”).group() 输出: ‘laowang@126.com’

  • re.match(r"[a-zA-Z0-9_]{4,20}@(163|126).com$",“laowang@126.com”).group(1) 输出: ‘126’

  • re.match(r"[a-zA-Z0-9_]{4,20}@(163|126).com$",“laowang@126.com”).group(0) 输出: ‘laowang@126.com’

  • re.match(r"([a-zA-Z0-9_]{4,20})@(163|126).com$",“laowang@126.com”).group(1) 输出: ‘laowang’

  • html_str = “<h1>hahaha</h1>”

  • re.match(r"<(\w*)>.*</\1>",html_str).group() 输出:’<h1>hahaha</h1>’

  • html_str = “<body><h1>hahaha</h1></body>”

  • re.match(r"<(\w*)><(\w*)>.*</\2></\1>",html_str).group() 输出:’<body><h1>hahaha</h1></body>’

  • re.search(r"\d+",“阅读数为 9999,点赞数为:100”).group() 输出: ‘9999’ 找出一个相匹配的

  • re.findall(r"\d+",“python=9999,c=8790,c++=12345”) 输出: [‘9999’, ‘8790’, ‘12345’] 找出所有匹配到的

  • re.sub(r"\d+",“998”,“python=997”) 输出: ‘python=998’

  • re.sub(r"\d+",“998”,“python=997,c++=1024”) 输出:‘python=998,c++=998’

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值