Python模块-re模块实例

一个葫芦瓢啊 / 2023-08-07 / 原文

正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并通过 re 模块实现。

import re
  • \w与\W

    • \w匹配字母数字及下划线
    re.findall('\w','hello world 2022_04/24')
    ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', '2', '0', '2', '2', '_', '0', '4', '2', '4']
    
    • \W匹配非字母数字下划线
    re.findall('\W','hello world 2022_04/22')
    [' ', ' ', '/']
    
  • \s与\S

    • \s匹配任意空白字符,等价于[\t,\n,\r,\f]
    re.findall('\s','hello world 2022_04/22')
    [' ', ' ']
    
    • \S匹配任意非空字符
    re.findall('\S','hello world 2022_04-24')
    ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', '2', '0', '2', '2', '_', '0', '4', '-', '2', '4']
    
  • \d与\D

    • \d匹配任意数字
    re.findall('\d','hello world 2022_04-24')
    ['2', '0', '2', '2', '0', '4', '2', '4']
    
    • \D匹配任意非数字
    re.findall('\D','hello world 2022_04-24')
    ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', '_', '-']
    
  • \A与\Z

    • \A匹配字符串开始
    re.findall('\Ah','hello world 2022_04-24')
    ['h']
    
    • \Z匹配字符串结束,如果存在换行,只匹配到换行前的结束字符串
    re.findall('24\Z','hello world 2022_04-24')
    ['24']
    
  • ^与$等价于\A与\Z

    • ^
    re.findall('^he','hello world 2022_04-24')
    ['he']
    
    • $
    re.findall('24$','hello world 2022_04-24')
    ['24']
    
  • 重复匹配:| . | * | ? | .* | .*? | + | {n,m} |

    • .中间只匹配一个字符,可以为空
    re.findall('o.w','leeleeeeeleeo worleee  ')
    ['o w']
    
    • *左侧字符0或无数个
    re.findall('ll*','leeleeeeeleeo worleee  ')
    ['l', 'l', 'l', 'l']
    
    • ?左侧字符0个或1个
    re.findall('el?','leeleeeeeleeo worleee  ')
    ['e', 'el', 'e', 'e', 'e', 'e', 'el', 'e', 'e', 'e', 'e', 'e']
    
    • +左侧字符1个或无穷个
    re.findall('ll+','leeleeeeeleeo worleee  ')
    []
    
    • {n,m}左侧字符最少重复n次,最多m次
    re.findall('le{2,4}','leeleeeeeleeo worleee  ')
    ['lee', 'leeee', 'lee', 'leee']
    
    • .*默认全部匹配
    re.findall('l.*l','leeleeeeeleeo worleee  ')
    ['leeleeeeeleeo worl']
    
    • .*?
    re.findall('l.*?l','leeleeeeeleeo worleee  ')
    ['leel', 'leeo worl']