您好,欢迎来到化拓教育网。
搜索
您的当前位置:首页Python 正则 —— 捕获与分组

Python 正则 —— 捕获与分组

来源:化拓教育网
  • \n:表示第 n 个捕获:

    >> s = "<html><h1>what the fuck!</h1></html>"
    >> p = r"<(.+)><(.+)>(.+)</\2></\1>"
                # \2 对应第二个捕获,也即 h1,则 </\2> 为:</h1>
                # \1 对应第一个捕获,也即 html,则 </\1> 为:</html>
    >> re.match(p, s).group(3)
    'what the fuck!'

1. 匹配邮箱与html标签

  • 匹配邮箱:

    >> mail = 'zch921005@126.com'
    >> reg = r"(\w{4,20})@(126|qq|gmail|163|outlook)\.(com)"
            # 正则表达式中不要出现无意义的空格
    >> re.match(reg, mail).group(1)
    'zch921005'
    >> re.match(reg, mail).group(2)
    '126'
    >> 
  • 匹配 html 标签:

    >> s='<div><a href="https://support.google.com/chrome/?p=ui_hotword_search" rel="external nofollow" target="_blank">更多</a><p>dfsl</p></div>'
    >> re.search(r'<a.*>(.*)</a>', s).group(1)
    '更多'

2. 起别名

>>> s = '<html><h1>what the fuck!</h1></html>'
>>> p = r"<(?P<key1>.+)><(?P<key2>.+)>(.+)</(?P=key2)></(?P=key1)>"
>> re.match(p, s).group(1)
'html'
>> re.match(p, s).group(2)
'h1'
>> re.match(p, s).group(3)
'what the fuck!'

转载于:https://www.cnblogs.com/mtcnn/p/9420949.html

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo9.cn 版权所有 赣ICP备2023008801号-1

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务