kllhi 发表于 2016-1-26 09:06:35

python 正则表达式

python 正则表达式

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

        .        匹配除换行符之外的任一字符;
        \w        匹配字母、数字、下划线、汉字;
        \s        匹配任一空白字符;
        \d        匹配数字;
        \b        匹配单词的开始或结束;
        ^        匹配字符串的开始,与其他连用表取反;
        $        匹配字符串的结束;

次数:

        *        重复零次或多次;
        +        重复一次或多次;
        ?        重复零次或一次;
        {n}        重复n次
        {n,m}        重复n到m次;

re 模块下 match 、search 、findall 、sub、split、group() 和 groups()方法

match: 从字符串开头开始匹配,匹配到一个即退出;

                >>> re.match(".","abc123def")
                <_sre.SRE_Match object; span=(0, 1), match='a'>
                >>> re.match(".","abc123def").group()
                'a'

search:

                >>> re.search("\d+","abc123def456upq").group()# 取第一组符合的数字
                '123'


findall:

                >>> re.findall("\d+","abc123def456upq")      #取所有数字
                ['123', '456']
                >>> re.findall("[^\d+]","abc123def456upq_jdh*jde345dfs")       # 取反
                ['a', 'b', 'c', 'd', 'e', 'f', 'u', 'p', 'q', '_', 'j', 'd', 'h', '*',
                'j', 'd', 'e', 'd', 'f', 's']
                >>>

sub :替换匹配的字符串

                >>> print(re.sub('\d+','|','sad45323sab$3@#24.7c_234',count=2))
                sad|sab$|@#24.7c_234

split:根据指定的匹配进行分组
                >>> tent
        "'1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )'"
                >>> re.split('\*',tent)
                ["'1 - 2 ", ' ((60-30+1', '(9-2', '5/3+7/3', '99/4', '2998+10', '568/14))
               -(-4', '3)/(16-3', "2) )'"]


group() 和 groups(): 以分组形式进行显示

                  >>> a = "123abc456"
                >>> print(re.search("(*)(*)(*)",a).group())
                123abc456
                >>> print(re.search("(*)(*)(*)",a).group(0))
                123abc456
                >>> print(re.search("(*)(*)(*)",a).group(1))
                123
                >>> print(re.search("(*)(*)(*)",a).group(2))
                abc
                >>> print(re.search("(*)(*)(*)",a).groups())
                ('123', 'abc', '456')


页: [1]
查看完整版本: python 正则表达式