zoukankan      html  css  js  c++  java
  • python笔记08-----正则表达式

    创建正则表达式对象

    import re

    常用匹配语法

    re.match 从头开始匹配

    re.search 匹配包含

    re.findall 把所有匹配到的字符放到以列表中的元素返回

    re.splitall 以匹配到的字符当做列表分隔符

    re.sub 匹配字符并替换

    re.compile(r'(ddd)-(ddd-dddd)')  创建匹配对象

    常用正则表达式符号

    . 默认匹配除 之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行

    ^ 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r”^a”,” abc eee”,flag=re.MULTILINE)

    $ 匹配字符串结尾,或e.search(”foo$”,”bfoo nsdfsf”,flags=re.MULTILINE).group()也可以

    * 匹配*号前的字符0次或多次,re.findall(“ab*”,”cabb3abcbbac”) 结果为[‘abb’,’ab’,’a’]

    + 匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba")       ['ab', 'abb']

    ? 匹配前一个字符1次或0次

    {m}匹配前一个字符m次 re.findall("b{3}","ab+cd+abbb+bba") ['bbb']

    {n,m} 匹配前一个字符n到m次 re.findall("b{1,2}","ab+cd+abbb+bba") ['b', 'bb', 'b', 'bb'] 后边加问好是匹配最少 不加则是最多

    | 匹配|左或|右的字符 re.findall("b|c","ab+cd+abbb+bba") ['b', 'c', 'b', 'b', 'b', 'b', 'b']

    (...)分组匹配

    A 只从字符开头匹配

     匹配字符结尾 同$

    d 匹配数字0-9

    D 匹配非数字

    w 匹配[A-Za-z0-9]

    W匹配非[A-Za-z0-9]

    s 匹配空白字符。

    S匹配除了空白字符。

     (?P<name>…)分组匹配

    匹配实例

    1.创建匹配对象compile()方法

    import re
    a = re.compile(r'd+')
    a1 = a.search('gfd12341ahvcnxjbkafa')
    print (a1.group())      # .group()直接输出结果,而不是返回对象

    结果

    12341

    2.从头开始匹配 match()方法

    import re
    a = re.match("^w.+", "wdasfdsafdsa1223fdssfd33311")
    b = re.match("^[a-z]+", "wdasfdsafdsa1223fdssfd33311")
    c = re.search("R[a-zA-z]+a", "wdasfdsafdsa1223fdssfd33311")
    print (a)
    print (b)
    print (c)

    结果如下

    <_sre.SRE_Match object; span=(0, 27), match='wdasfdsafdsa1223fdssfd33311'>
    <_sre.SRE_Match object; span=(0, 12), match='wdasfdsafdsa'>
    None

    3.匹配包含search()方法

    import re
    a = re.search("[a-z]+","abcdefg12345")

    print (a.group())

    结果如下

    abcdefg

    4.管道匹配多个分组 |

    import re
    hero = re.compile(r'ABC|DEF')
    m1 = hero.search('ABC hehe ABC')
    print (m1.group())
    m2 = hero.search('DEF hehe ABC')
    print (m2.group())

    结果如下

    ABC
    DEF

    5.分组匹配 () 和group()

    import re

    phoneNum = re.compile(r'(ddd)-(ddd-dddd)')
    mo = phoneNum.search('my number is 415-555-4242')
    print (mo.group(1))          #输出第一个组
    print (mo.group(2))          #输出第二个组
    print (mo.group(0))          #输出所有
    print (mo.group())            #输出所有

    结果

    415
    555-4242
    415-555-4242
    415-555-4242

    6.用问号实现可选匹配

    import re
    b = re.compile(r'Bat(wo)?man')
    mo = b.search('The Adventures of Batman')
    print (mo.group())
    mo1 = b.search('The Adventures of Batwoman')
    print (mo1.group())

    结果

    Batman

    Batwoman

    7.用星号匹配零次或多次

    import re

    b = re.compile(r'Bat(wo)*man')
    mo = b.search('The Adventures of Batman')
    print (mo.group())
    mo1 = b.search('The Adventures of Batwoman')
    print (mo1.group())
    mo2 = b.search('The Adventures of Batwowowowowoman')
    print (mo2.group())

    结果

    Batman
    Batwoman
    Batwowowowowoman

    8.用+号匹配一次或多次

    import re

    b = re.compile(r'Bat(wo)+man')
    mo = b.search('The Adventures of Batwoman')
    print (mo.group())
    mo1 = b.search('The Adventures of Batwoman')
    print (mo1.group())
    mo2 = b.search('The Adventures of Batwowowowowoman')
    print (mo2.group())

    结果

    Batwoman

    Batwoman

    Batwowowowowoman

    9.用花括号匹配特定次数

    import re

    b = re.compile(r'(ha){3}')
    mo = b.search('hahahahahaha')
    print (mo.group())

    结果

    hahaha

    10.花括号匹配最多和最少次数

    import re

    b = re.compile(r'(ha){3,5}')              #匹配3到5次
    mo = b.search('hahahahahaha')     #什么都不加默认匹配最多个
    print (mo.group())
    b1 = re.compile(r'(ha){3,5}?')            #加问号匹配最少的个数
    mo1 = b1.search('hahahahahaha')
    print (mo1.group())

    结果

    hahahahaha
    hahaha

    11.findall()方法

    import re
    b = re.compile(r'dddd-dddd')
    mo = b.findall('call: 1234-4321 work:8521-5155')
    print (mo)

    返回结果列表

    ['1234-4321', '8521-5155']

    分组匹配

    import re
    b = re.compile(r'(dddd)-(dddd)')
    mo = b.findall('call: 1234-4321 work:8521-5155')
    print (mo)

    返回结果列表 元组

    [('1234', '4321'), ('8521', '5155')]

    12.建立自己的字符分类

    匹配[]中的元素 和匹配除[]中的元素

    import re

    v = re.compile(r'[^abc]')
    v1 = v.findall('gafeagbbbbfsdgfaccsgzfevcsdfdf')
    print (v1)
    q = re.compile(r'[abc]')
    q1 = q.findall('gafeagbbbbfsdgfaccsgzfevcsdfdf')
    print (q1)

     

    结果

    ['g', 'f', 'e', 'g', 'f', 's', 'd', 'g', 'f', 's', 'g', 'z', 'f', 'e', 'v', 's', 'd', 'f', 'd', 'f']

    ['a', 'a', 'b', 'b', 'b', 'b', 'a', 'c', 'c', 'c']

    13.不区分大小写匹配 re.IGNORECASE或re.I

    import re
    a = re.compile(r'efg', re.I)
    print (a.search('ABCDEFG').group())
    结果
    EFG

    14.sub()方法替换字符串

    import re

    a = re.compile(r'ABC')

    print (a.sub(r'123','ABCDEFG'))

    结果

    123DEFG

    sub支持函数调用

    import re

    def add(tmp):

      strnum = tmp.group()

      num = int(strnum) + 1

      return str(num)

    ret = re.sub(r'd+', add, "python = 123")

    print (ret)

    ret = re.sub(r'd+', add, "python = 12")

    print (ret)

    输出结果

    python = 124

    python = 13

    15.管理复杂的正则表达式re.VERBOSE

    import re
    a = re.compile(r'''(
        (d{3}|(d{3}))?   #注释
        )''',re.VERBOSE)
    b = a.search('123,32141,321,fdsafdgdacszc')
    print (b.group())

    看结果

    123

     16.split根据匹配进行切割字符串,并返回一个列表

    import re

    ret = re.split(r":| ", "oh:my:god | nonono")

    print (ret)

    ['oh', 'my', 'god ' ,'nonono']

    正则表达式符号总结

    ? 匹配零次或一次前面的分组

    *  匹配零次或多次前面的分组

    + 匹配一次或多次前面的分组

    {n} 匹配n次前面的分组

    {n,} 匹配n次或更多前面的分组

    {,m} 匹配零次到m次前面的分组

    {n,m} 匹配至少n次,至多m次前面的分组

    {n,m} ?或*?或+?对前面的分组进行最少/最多次匹配

    ^spam 意味着字符串必须以spam开始

    spam$ 意味着字符串必须以spam结束

    . 匹配所有字符,换行符除外

    d w s 分别匹配数字,单词和空格

    D W S 分别匹配出数字,单词和空格外的所有字符

    [abc] 匹配中括号内的任意字符(a,b或c)

    [^abc] 匹配不在中括号内的任意字符

     如果想匹配. * +这样的字符 请用转义字符\,如. *  + 

    其他的匹配符号大家可以自己去组合去尝试,这里不一一列举了

    练习:校验手机号

    import re
    
    r = re.compile(r'^1[3-9][0-9]{9}$')
    
    print(r.match("12345678911"))
    print(r.match("13333333333"))
    print(r.match("13671273333"))
    print(r.match("1a222222222"))
    print(r.match("17600259711"))

    结果为

    None
    <re.Match object; span=(0, 11), match='13333333333'>
    <re.Match object; span=(0, 11), match='13671273333'>
    None
    <re.Match object; span=(0, 11), match='17600259711'>

  • 相关阅读:
    定义通用类型,便于移植和32位、64位的编译
    映射密码的加密,解密以及暴力破解
    位移密码的加密,解密以及暴力破解
    TCP三次握手和四次挥手通俗理解
    git常用命令
    pip及npm换源
    win10安装Docker并换国内源
    搜索引擎工作原理
    wsgi_uwsgi_nginx理论知识
    课程全文检索接口
  • 原文地址:https://www.cnblogs.com/wsy1030/p/8961414.html
Copyright © 2011-2022 走看看