zoukankan      html  css  js  c++  java
  • Python3学习之路~5.13 re模块 正则表达式

    re模块用于对python的正则表达式的操作。

    常用正则表达式符号

    字符数字:
    
      . 匹配除换行符以外的任意字符,即[^
    ]
      s 匹配任意空白符(如	、
    、
     )
      S 匹配任意非空白符
        w 匹配[A-Za-z0-9下划线汉字]
        W 匹配非[A-Za-z0-9下划线汉字]
       匹配单词的开始或结束
      ^或A 匹配字符串的开始
      $或 匹配字符串的结束
      d或[0-9] 匹配所有数字
        D 匹配非数字
    
    次数:
    
      * 重复零次或多次
      + 重复一次或多次
      ? 重复零次或一次
      {n} 重复n次
      {n,} 重复n次或更多次
      {n,m} 重复n到m次
    
    其他:
        | 匹配|左或|右的字符
        (...) 分组匹配
         转义字符
        [] 匹配符合[]内的字符
        [^] 匹配不符合[]内的字符
    组合:
        (?P<name>...) 分组匹配    
        [a-z] 匹配所有小写字母字符
        [^a-z] 匹配所有非小写字母字符
      [^0-9] 匹配所有非数字字符
        [u4e00-u9fa5] 匹配中文
        (.*)或(.+) 匹配单行
        ^(25[0-5]|2[0-4]d|[0-1]?d?d)(.(25[0-5]|2[0-4]d|[0-1]?d?d)){3}$ 匹配IP
        ^1[3|4|5|7|8|9][0-9]d{8}$ 匹配手机号(貌似手机号第二位有3,4,5,7,8,9)

    正则表达式代码实例

    import re
    
    # . 匹配除换行符以外的任意字符,即[^
    ]
    # + 重复一次或更多次
    # .+匹配任意字符串
    res = re.search('f.+n',"abcd1234efghijklmn5678")
    print(res.group())  # fghijklmn
    
    # s 匹配任意空白符(如	、
    、
     )
    res = re.search('s+',"123$+ 
       b")
    print(res.group())  #   ' 
    	'
    
    # S 匹配任意非空白符
    res = re.search('S+',"123aZ你好$+ 
       b")
    print(res.group())  # 123aZ你好$+
    
    # w 匹配[A-Za-z0-9下划线汉字]
    res = re.search('w+',"123_你好$+ b")
    print(res.group())  #   123_你好
    
    # W 匹配非[A-Za-z0-9下划线汉字]
    res = re.search('W+',"123_你好$+ b")
    print(res.group())  #   $+
    
    # ^或A    匹配字符串的开始
    # $或 匹配字符串的结束
    res = re.search('A[0-9]+[a-z]',"123b")
    print(res.group())  #   123b
    
    res = re.search('^[0-9]+[a-z]$',"123b")
    print(res.group())  #   123b
    
    # d或[0-9]    匹配所有数字
    res = re.search('abcdd',"abcd1234efgh5678")
    print(res.group())  # abcd1
    
    res = re.search('abcd[0-9]',"abcd1234efgh5678")
    print(res.group())  # abcd1
    
    # D 匹配非数字
    res = re.search('D+',"123$+ b")
    print(res.group())  #   $+ b
    
    # ?    重复零次或一次
    res = re.search('aal?',"aalex") # 匹配aa或者aal
    print(res.group())  #   aal
    
    res = re.search('aal?',"aaex")
    print(res.group())  #   aa
    
    # * 重复零次或多次
    # {n}    重复n次
    # {n,}    重复n次或更多次
    # {n,m}    重复n到m次
    res = re.search('e[0-9]*',"aa1e2345x")
    print(res.group())  #   e2345
    
    res = re.search('[0-9]{3}',"aa1e2345x")
    print(res.group())  #   234
    
    res = re.search('[0-9]{3,}',"aa1e2345x")
    print(res.group())  #   2345
    
    res = re.search('[0-9]{1,3}',"aa1e2345x")
    print(res.group())  #   1
    
    # | 匹配|左或|右的字符
    res = re.search('abc|ABC',"ABCdabcD")
    print(res.group())  #   ABC
    
    # (...) 分组匹配
    res = re.search('abc{2}',"Alexabcc") #匹配c两次
    print(res.group())  #   abcc
    
    res = re.search('(abc){2}',"Alexabcabc") #匹配abc两次
    print(res.group())  #   abcabc
    
    #  转义字符
    res = re.search(r"\","abcd12s3df4sa5f")
    print(res.group())  # 
    
    res = re.search("\\","abcd12s3\df4sa5f")
    print(res.group())  # 
    
    res = re.search('(abc){2}|',"Alexabcabc|") #匹配管道符,前面需加反斜杠转义
    print(res.group())  #   abcabc|
    
    res = re.search('(abc){2}(||=){2}',"Alexabcabc||=||=") #等号不需转义
    print(res.group())  #   abcabc||=||=
    
    # (?P < name >...) 分组匹配
    res = re.search("(?P<id>[0-9]+)","abcd1234sdfsaf")
    print(res.groupdict())  # {'id': '1234'}
    
    res = re.search("(?P<id>[0-9]+)(?P<name>[a-zA-Z]+)","abcd1234sdfs#2af")
    print(res.groupdict())  # {'id': '1234', 'name': 'sdfs'}
    a=res.groupdict()
    print(a['id']) # 1234
    a =res.group('id')
    print(a) # 1234
    
    res = re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{8})","371102199211186666")
    print(res.groupdict())  # {'province': '3711', 'city': '02', 'birthday': '19921118'}
    
    # [a-z] 匹配所有小写字母字符
    res = re.search('[a-z]+',"ABCD1234abcd&*")
    print(res.group())  #   abcd
    
    # [^a-z] 匹配所有非小写字母字符
    res = re.search('[^a-z]+',"ABCD1234abcd&*")
    print(res.group())  #   ABCD1234
    
    # [^0-9] 匹配所有非数字字符
    res = re.search('[^0-9]+',"ABCDabcd&*1234")
    print(res.group())  #  ABCDabcd&*
    
    # [u4e00-u9fa5] 匹配中文
    res = re.search('[u4e00-u9fa5]+',"ABCDabcd&*1234你好")
    print(res.group())  #  你好
    
    # (.*)或(.+) 匹配单行
    res = re.search('(.*)',"ABCDabc
    d&*1
    234你好")
    print(res.group())  #  ABCDabc
    
    res = re.search('(.+)',"ABCDabc
    d&*1
    234你好")
    print(res.group())  #  ABCDabc
    
    # ^(25[0-5]|2[0-4]d|[0-1]?d?d)(.(25[0-5]|2[0-4]d|[0-1]?d?d)){3}$ 匹配IP
    res = re.search('^(25[0-5]|2[0-4]d|[0-1]?d?d)(.(25[0-5]|2[0-4]d|[0-1]?d?d)){3}$',"192.168.1.10")
    if res:
        print(res.group())  #  192.168.1.10
    else:
        print('it is not a valid IP')
    
    # ^1[3|4|5|8][0-9]d{8}$ 匹配手机号
    res = re.search('^1[3|4|5|7|8|9][0-9]d{8}$',"18710602222")
    if res:
        print(res.group())  # 18710602222
    else:
        print('it is not a valid phone number')
    View Code

    re模块中最常用的匹配语法

    1、match(pattern, string, flags=0)    从起始位置开始根据模型去字符串中匹配指定内容,匹配单个

    • 正则表达式
    • 要匹配的字符串
    • 标志位,用于控制正则表达式的匹配方式
    import re
    
    res = re.match('d+', '123uuasf')
    if res:
        print(res.group()) # 123

    2、search(pattern, string, flags=0)    根据模型去字符串中匹配指定内容,匹配单个

    import re
    
    res = re.search('d+', 'aa123uuasf')
    if res:
        print(res.group()) # 123

    3、findall(pattern, string, flags=0)    根据模型去字符串中匹配指定内容,匹配所有。注意:findall没有group方法。

    import re
    
    res = re.findall('d+', 'fa123uu888asf')
    if res:
        print(res) # ['123', '888']

    4、sub(pattern, repl, string, count=0, flags=0)    用于替换匹配的字符串,相比于str.replace功能更加强大

    import re
    
    res = re.sub("[0-9]+","|","abcd12s3df4sa5f")
    print(res)  # abcd|s|df|sa|f
    
    res = re.sub("[0-9]+","|","abcd12s3df4sa5f",count=2)
    print(res)  # abcd|s|df4sa5f

    5、split(pattern, string, maxsplit=0, flags=0)    根据指定匹配进行分组,相比于str.split更加强大  

    import re
    res = re.split("[0-9]+","abcd12s3df4sa5f")
    print(res)  # ['abcd', 's', 'df', 'sa', 'f']

    6、group和groups

    import re
    a = "123abc456"
    print(re.search("([0-9]*)([a-z]*)([0-9]*)", a).group()) # 123abc456
    
    print(re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(0)) # 123abc456
    print(re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(1)) # 123
    print(re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(2)) # abc
    
    print(re.search("([0-9]*)([a-z]*)([0-9]*)", a).groups()) # ('123', 'abc', '456')

    几个匹配模式

    # flags
    I = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # 忽略大小写
    M = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # 多行模式,可改变'^'和'$'的行为
    S = DOTALL = sre_compile.SRE_FLAG_DOTALL # 点任意匹配模式,可改变'.'的行为
    L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
    U = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode locale
    X = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
    import re
    
    # I = IGNORECASE 忽略大小写
    res = re.search("[a-z]+","abcdA123",flags=re.I)
    print(res.group())  # abcdA
    
    # M = MULTILINE 多行模式,可改变'^'和'$'的行为
    res = re.search("^[a-z]+","
    abcd12
    A123",flags=re.M)
    print(res.group())  # abcd 若不加flags=re.M则abcd是匹配不出来的
    
    res = re.search("foo$","
    bfoo
    sdfsf",flags=re.M)
    print(res.group())  # foo 不加flags=re.M则foo是匹配不出来的
    
    # S = DOTALL 点任意匹配模式,可改变'.'的行为
    msg = '''abc
    123
    '''
    res = re.search("^.+",msg,flags=re.S)
    print(res.group())  #由于msg中abc和123占2行,如果不加flags=re.S则只能匹配一行abc
    # 输出:
    # abc
    # 123
    匹配模式举例

    反斜杠的困扰

    与大多数编程语言相同,正则表达式里使用""作为转义字符,这就可能造成反斜杠困扰。假如你需要匹配文本中的字符"",那么使用编程语言表示的正则表达式里将需要4个反斜杠"\\":前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠。Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可以使用r"\"表示。同样,匹配一个数字的"\d"可以写成r"d"。有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。

  • 相关阅读:
    MongoDB性能分析
    MongoDB复制
    redis键管理
    MySQL集群架构-DRBD+headbeat +lvs+keepalived
    Spark-Core RDD转换算子-双Value型交互
    Spark-Core RDD转换算子-Value型
    Spark-Core RDD的创建
    Spark-Core RDD概述
    数仓理论
    flume 进阶
  • 原文地址:https://www.cnblogs.com/zhengna/p/9237012.html
Copyright © 2011-2022 走看看