Python re正则表达式学习

发布时间:2019-08-24 09:29:18编辑:auto阅读(1049)

    一、re.match
    re.match 尝试从字符串的开始匹配一个模式,如:下面的例子匹配第一个单词。

    import re  
    text = "JGood is a handsome boy, he is cool, clever, and so on..."
    m = re.match(r"(\w+)\s", text)  
    if m:  
        print m.group(0), '\n', m.group(1)  
    else:  
        print 'not match'
    re.match的函数原型为:re.match(pattern, string, flags)

    第一个参数是正则表达式,这里为"(\w+)\s",如果匹配成功,则返回一个Match,否则返回一个None;

    第二个参数表示要匹配的字符串;

    第三个参数是标致位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。

     

    二、re.search
    re.search函数会在字符串内查找模式匹配,只到找到第一个匹配然后返回,如果字符串没有匹配,则返回None。

    import re  
    text = "JGood is a handsome boy, he is cool, clever, and so on..."
    m = re.search(r'\shan(ds)ome\s', text)  
    if m:  
        print m.group(0), m.group(1)  
    else:  
        print 'not search'
    re.search的函数原型为: re.search(pattern, string, flags)

    每个参数的含意与re.match一样。

    re.match与re.search的区别:re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。

     

    三、re.sub
    re.sub用于替换字符串中的匹配项。下面一个例子将字符串中的空格 ' ' 替换成 '-' :

    import re  
    text = "JGood is a handsome boy, he is cool, clever, and so on..."
    print re.sub(r'\s+', '-', text)
    re.sub的函数原型为:re.sub(pattern, repl, string, count)

    其中第二个函数是替换后的字符串;本例中为'-'

    第四个参数指替换个数。默认为0,表示每个匹配项都替换。

    re.sub还允许使用函数对匹配项的替换进行复杂的处理。如:re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0);将字符串中的空格' '替换为'[ ]'。

     

    四、re.split
    可以使用re.split来分割字符串,如:re.split(r'\s+', text);将字符串按空格分割成一个单词列表。

     

    五、re.findall
    re.findall可以获取字符串中所有匹配的字符串。如:re.findall(r'\w*oo\w*', text);获取字符串中,包含'oo'的所有单词。

     

    六、re.compile
    可以把正则表达式编译成一个正则表达式对象。可以把那些经常使用的正则表达式编译成正则表达式对象,这样可以提高一定的效率。下面是一个正则表达式对象的一个例子:

    import re  
    text = "JGood is a handsome boy, he is cool, clever, and so on..."
    regex = re.compile(r'\w*oo\w*')  
    print regex.findall(text)   #查找所有包含'oo'的单词  
    print regex.sub(lambda m: '[' + m.group(0) + ']', text) #将字符串中含有'oo'的单词用[]括起来。

     

    七、group()

      1.group([group1,…])

      返回匹配到的一个或者多个子组。如果是一个参数,那么结果就是一个字符串,如果是多个参数,那么结果就是一个参数一个item的元组。group1的 默认值为0(将返回所有的匹配值).如果groupN参数为0,相对应的返回值就是全部匹配的字符串,如果group1的值是[1…99]范围之内的,那 么将匹配对应括号组的字符串。如果组号是负的或者比pattern中定义的组号大,那么将抛出IndexError异常。如果pattern没有匹配到, 但是group匹配到了,那么group的值也为None。如果一个pattern可以匹配多个,那么组对应的是样式匹配的最后一个。另外,子组是根据括 号从左向右来进行区分的。

     >>> m=re.match("(\w+) (\w+)","abcd efgh, chaj")

     >>> m.group()            # 匹配全部

     'abcd efgh'

     >>> m.group(1)     # 第一个括号的子组.

     'abcd'

     >>> m.group(2)

     'efgh'

     >>> m.group(1,2)           # 多个参数返回一个元组

     ('abcd', 'efgh')

     >>> m=re.match("(?P<first_name>\w+) (?P<last_name>\w+)","sam lee")
    >>> m.group("first_name")  #使用group获取含有name的子组
    'sam'
    >>> m.group("last_name")
    'lee'

     

     下面把括号去掉

     >>> m=re.match("\w+ \w+","abcd efgh, chaj")

     >>> m.group()

     'abcd efgh'

     >>> m.group(1)

     Traceback (most recent call last):

       File "<pyshell#32>", line 1, in <module>

       m.group(1)

     IndexError: no such group

     

     If a group matches multiple times, only the last match is accessible:

       如果一个组匹配多个,那么仅仅返回匹配的最后一个的。

     >>> m=re.match(r"(..)+","a1b2c3")

     >>> m.group(1)

     'c3'

     >>> m.group()

     'a1b2c3'

     Group的默认值为0,返回正则表达式pattern匹配到的字符串

     

     >>> s="afkak1aafal12345adadsfa"

     >>> pattern=r"(\d)\w+(\d{2})\w"

     >>> m=re.match(pattern,s)

     >>> print m

     None

     >>> m=re.search(pattern,s)

     >>> m

     <_sre.SRE_Match object at 0x00C2FDA0>

     >>> m.group()

     '1aafal12345a'

     >>> m.group(1)

     '1'

     >>> m.group(2)

     '45'

     >>> m.group(1,2,0)

     ('1', '45', '1aafal12345a')

      

      2.groups([default])

     返回一个包含所有子组的元组。Default是用来设置没有匹配到组的默认值的。Default默认是"None”,

     >>> m=re.match("(\d+)\.(\d+)","23.123")

     >>> m.groups()

     ('23', '123')

     >>> m=re.match("(\d+)\.?(\d+)?","24") #这里的第二个\d没有匹配到,使用默认值"None"

     >>> m.groups()

     ('24', None)

     >>> m.groups("0")

     ('24', '0')

     

     3.groupdict([default])

     返回匹配到的所有命名子组的字典。Key是name值,value是匹配到的值。参数default是没有匹配到的子组的默认值。这里与groups()方法的参数是一样的。默认值为None

     >>> m=re.match("(\w+) (\w+)","hello world")

     >>> m.groupdict()

     {}

     >>> m=re.match("(?P<first>\w+) (?P<secode>\w+)","hello world")

     >>> m.groupdict()

     {'secode': 'world', 'first': 'hello'}

     通过上例可以看出,groupdict()对没有name的子组不起作用

关键字