zoukankan      html  css  js  c++  java
  • 正则表达式快速入门

    前言

    python文档:https://docs.python.org/zh-cn/3/library/re.html?highlight=re#module-re

    findall:匹配所有符合条件的内容。

    search:匹配第一个符合条件的内容。

    sub:替换符合条件的内容

    1.".":匹配任意字符,换行符" "除外

    import re
    
    a='yasdfhs'
    
    c=re.findall('y.',a)
    print(c)    #输出['ya']
    
    e=re.findall('y..',a)
    print(e)   #['yas']
    
    b=re.findall('y...',a)
    print(b)   #输出['yasd']

    如果被匹配的字符串中有换行符" "

    import re
    
    b="hello
    world"
    a=re.findall("o.",b)
    print(a)    #输出['or']
    
    w="helloworld"
    d=re.findall("o.",w)
    print(d)    #输出['ow', 'or']

    2.“*”:匹配前一个字符(0次或无数次)

       "?":匹配前一个字符(1次或0次)

    二者的区别就在于下边的例子:

    import re

    a='hyyssyy'
    c=re.findall('s*',a) print(c) #输出 ['', '', '', 'ss', '', '', ''] w=re.findall("s?",a) print(w) #输出 ['', '', '', 's', 's', '', '', ''] # 如果在字符和字符串之间加空格 c=re.findall('s *',a) print(c) #输出 ['s', 's'] w=re.findall("s ?",a) print(w) #输出['s', 's'] #很显然,"*"和"?"都不会匹配空格代表的内容

    3.".*":贪心算法(尽可能匹配多的符合条件的内容)

     “.*?”:非贪心算法(尽可能匹配较少的符合条件的内容)

     "()":把括号内的数据作为结果输出

    二者的区别就在于下边的例子:

    import re 
    
    a_cod="xxxixxxxxxlikexxxxxxpythonxxx"
    
    g=re.findall('xxx.*xxx',a_cod)
    print(g)    #输出['xxxixxxxxxlikexxxxxxpythonxxx']
    
    s=re.findall('xxx(.*)xxx',a_cod)
    print(s)    #输出['ixxxxxxlikexxxxxxpython']
    
    d=re.findall('xxx.*?xxx',a_cod)
    print(d)    #输出['xxxixxx', 'xxxlikexxx', 'xxxpythonxxx']
    
    h=re.findall('xxx(.*?)xxx',a_cod)
    print(h)    #输出['i', 'like', 'python']
    
    #加入小括号"()"的作用一目了然,目的是为了使其只显示符合条件的目标的内容,增加美观度。

    4.“S”:使条件语句能够匹配空格,换行等等

    import re
    
    a_cod='''xhelloxx
    pythonxx!x'''
    
    d=re.findall('x(.*?)x',a_cod)
    print(d)    #输出['hello', '']
    
    a=re.findall('x(.*?)x',a_cod,re.S)
    print(a)    #输出['hello', '
    python', '!']

    5.对比'findall'和'search'函数

    import re
    
    a_cod='''xhelloxx
    pythonxx!x'''
    
    a=re.search('x(.*?)x',a_cod,re.S)
    print(a)    #输出<re.Match object; span=(0, 7), match='xhellox'>
    
    #"search"中只匹配了“hello”
    
    q=re.findall('x(.*?)x',a_cod,re.S)
    print(q)    #输出['hello', '
    python', '!']

    6.“sub”:替代

    import re
    
    a='1xxx1'
    
    s=re.sub('1(.*?)1','456',a)
    print(s)    #输出456
    
    d=re.sub('1(.*?)1','1%s1','asddf')
    print(d)    #输出asddf

    以上就是正则表达式快速入门的几个常用方法,学会以上方法的就可以尝试制作简单的爬虫

    如有不足,欢迎大家指出!

  • 相关阅读:
    jenkins更换国内源
    部署jdk和maven
    Prometheus监控Nginx
    Prometheus监控MySQL
    MySql里动态视图的实现
    MySql里split函数的实现
    HTML编码规范
    消弱反驳18招
    Pr2020
    记忆准则
  • 原文地址:https://www.cnblogs.com/wangwenchao/p/11827912.html
Copyright © 2011-2022 走看看