zoukankan      html  css  js  c++  java
  • Python正则表达式re

    字符组 : [字符组]

    在同一个位置可能出现的各种字符组成了一个字符组,在正则表达式中用[]表示 字符分为很多类,比如数字、字母、标点等等。

    1 [1]                       匹配1
    2 [123]        匹配1、23
    3 [0-9]       匹配任意一个数字
    4 [a-z]       匹配任意一个小写字母
    5 [A-Z]       匹配任意一个大写字母
    6 [A-Za-z]      匹配任意一个字母

    示例如下:

    print(re.findall('[1]','Zll5201314'))       #['1', '1']
    print(re.findall('[123]','Zll5201314'))     #['2', '1', '3', '1']
    print(re.findall('[0-9]','Zll5201314'))     #['5', '2', '0', '1', '3', '1', '4']
    print(re.findall('[a-z]','Zll5201314'))     #['l', 'l']
    print(re.findall('[A-Z]','Zll5201314'))     #['Z']
    print(re.findall('[a-zA-Z]','Zll5201314'))  #['Z', 'l', 'l']
    print(re.findall('[A-Za-z0-3]','Zll5201314')) #['Z', 'l', 'l', '2', '0', '1', '3', '1']

    元字符:

    .    匹配除换行符以外的任意字符
    w    匹配字母或者数字或者下划线
    s     匹配任意空白字符
    d     匹配数字
    
         匹配换行符
    	    匹配制表符tab
        匹配一个单词的结尾
    ^    匹配字符串的开始
    $    匹配字符串的结尾
    W   匹配非字母或下划线或数字
    D   匹配非数字
    S   匹配非空白符
    |    匹配|前或者后的内容
    ()    匹配括号内的表达式,也表示一个组

    示例如下:

    print(re.findall('.','love_u 520')) #['l', 'o', 'v', 'e', '_', 'u', ' ', '5', '2', '0']
    print(re.findall('w','love_u 520')) #['l', 'o', 'v', 'e', '_', 'u', '5', '2', '0']
    print(re.findall('s','love_u 520')) #[' ']
    print(re.findall('d','love_u 520')) #['5', '2', '0']
    print(re.findall('
    ','love_u 520')) #[]
    print(re.findall('','love_u 520')) #[]
    print(re.findall('^l','love_u 520')) #['l']
    print(re.findall('520$','love_u 520'))#['520']
    print(re.findall('W','love_u 520')) #[' ']
    print(re.findall('D','love_u 520')) #['l', 'o', 'v', 'e', '_', 'u', ' ']
    print(re.findall('S','love_u 520')) #['l', 'o', 'v', 'e', '_', 'u', '5', '2', '0']
    print(re.findall('love|u','love_u 520')) #['love', 'u']

    量词:

    n+ 匹配任何包含至少一个 n 的字符串。
    n* 匹配任何包含零个或多个 n 的字符串。
    n? 匹配任何包含零个或一个 n 的字符串。
    n$ 匹配任何结尾为 n 的字符串。
    ^n 匹配任何开头为 n 的字符串。
    ?=n 匹配任何其后紧接指定字符串 n 的字符串。
    ?!n 匹配任何其后没有紧接指定字符串 n 的字符串。
    1 print(re.findall('5*','555 5')) #['555', '', '5', '']
    2 print(re.findall('5+','555 5')) #['555', '5']
    3 print(re.findall('5?','555 5')) #['5', '5', '5', '', '5', '']
  • 相关阅读:
    使用CustomValidate自定义验证控件
    C#中金额的大小写转换
    Andriod出错之Unable to build: the file dx.jar was not loaded from the SDK folder!
    VC 编写的打字练习
    机房工作笔记Ping只有单向通
    web服务协同学习笔记(1)
    Dll 学习3 将MDI子窗口封装在DLL中
    机房工作学习文件共享
    Andriod出错之Failed to find an AVD compatible with target 'Android 2.2'
    Andriod出错之wrapper was not properly loaded first
  • 原文地址:https://www.cnblogs.com/menghen/p/9897309.html
Copyright © 2011-2022 走看看