Python day19_正则

作者: g_s_007 | 来源:发表于2018-05-27 23:15 被阅读0次
     .  匹配任意1个字符(除了\n)
     [ ]    匹配[ ]中列举的字符
     \d 匹配数字,即0-9
     \D 匹配非数字,即不是数字
     \s 匹配空白,即 空格,tab键
     \S 匹配非空白
     \w 匹配单词字符,即a-z、A-Z、0-9、_
     \W 匹配非单词字符
     *  匹配前一个字符出现0次或者无限次,即可有可无
     +  匹配前一个字符出现1次或者无限次,即至少有1次
     ?  匹配前一个字符出现1次或者0次,即要么有1次,要么没有
     {m}    匹配前一个字符出现m次
     {m,n}  匹配前一个字符出现从m到n次
     ^: 表示以什么字符串开头
    $ :表示以什么结尾
     |  匹配左右任意一个表达式
     (ab)   将括号中字符作为一个分组  
     \num   引用分组num匹配到的字符串
     (?P<name>) 分组起别名
     (?P=name)  引用别名为name分组匹配到的字符串
     re.search() 只查找一个
     re.findall() 查找所有匹配字符
     re.sub() 替换字符
    

    注意 尽量在正则表达式的外面加上r 如:r'\d+' 避免匹配中遇到\反斜杠转义

    模块: import re

    举例:

    匹配邮箱:

    # 把邮箱类型作为一个分组: (分组数据)
    match_obj = re.match("[a-zA-Z0-9_]{4,20}@(163|126|qq|sina)\.com$", "hello@163.com")
    if match_obj:
        print(match_obj.group())
        # 表示获取第一个分组的数据
        print(match_obj.group(1))
    else:
        print("匹配失败")
    

    匹配网页地址:

    方式一:

    # <html>hh</html>
    match_obj = re.match("<[a-zA-z0-9]+>.*</[a-zA-z0-9]+>", "<html>hh</html>")
    if match_obj:
        print(match_obj.group())
    else:
        print("匹配失败")
    

    方式二:

    # 引用分组匹配的数据: \num
    match_obj = re.match(r"<([a-zA-z0-9]+)>.*</\1>", "<html>hh</html>")
    if match_obj:
        print(match_obj.group())
    else:
        print("匹配失败")
    

    匹配网页地址:

    import re
    
    
    img_url = """<img alt="16圆圆儿的直播" data-original="https://rpic.douyucdn.cn/live-cover/appCovers/2018/04/15/3986928_20180415144934_big.jpg" src="https://rpic.douyucdn.cn/live-cover/appCovers/2018/04/15/3986928_20180415144934_big.jpg" width="283" height="163" class="JS_listthumb" style="display: block;">"""
    # python默认是贪婪的根据正则表达式尽量多匹配数据
    # 使用非贪婪: 尽量根据正则少匹配数据, 非贪婪的模式范围正则表达式后面加上?: 比如*?, +?, ??
    
    # 提示: 如果匹配的数据比预想的数据要多这个时候需要想到非贪婪 比如*?, +?, ??
    

    match_obj = re.search(r"https?://.*?.jpg", img_url)
    if match_obj:
    result = match_obj.group()
    print(result)
    else:
    print("匹配失败")

    相关文章

      网友评论

        本文标题:Python day19_正则

        本文链接:https://www.haomeiwen.com/subject/nngijftx.html