37 Python 正则表达式学习笔记

来源:互联网 发布:vb语言基础教程 编辑:程序博客网 时间:2024/06/04 23:35

本文为学习Python正则表达式笔记,主要基于(http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html)。

正则表达式通常用于在文本中查找匹配的字符串,是处理字符串的强大工具,拥有自己独特的语法以及独立的处理引擎,效率上可能不如str自带的方法,但功能十分强大。

原生字符串

原生字符串:Python中字符串前面加上 r。

与大多数编程语言相同,正则表达式里使用”\”作为转义字符,这就可能造成反斜杠困扰。

假如需要匹配文本中的字符”\”,正常情况下正则表达式里需要4个反斜杠”\\”:前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠。

Python里的原生字符串很好地解决了这个问题,使用”\”时无需转义,直接使用即可,如想匹配文本中的字符”\”

import reprint '\\'                   #\print r'\\'                  #\\s = '\\ab\\'print re.findall('\\\\',s)   #['\\', '\\']#使用原生字符串,与上面的等价print re.findall(r'\\',s)    #['\\', '\\']s = '1a2'print re.findall('\\d',s)    #['1', '2']#使用原生字符串,与上面的等价print re.findall(r'\d',s)    #['1', '2']

有了原生字符串,写出来的正则表达式更直观。

Python支持的正则表达式元字符和语法

The special characters are:    "."      Matches any character except a newline.    "^"      Matches the start of the string.    "$"      Matches the end of the string or just before the newline at             the end of the string.    "*"      Matches 0 or more (greedy) repetitions of the preceding RE.             Greedy means that it will match as many repetitions as possible.    "+"      Matches 1 or more (greedy) repetitions of the preceding RE.    "?"      Matches 0 or 1 (greedy) of the preceding RE.    *?,+?,?? Non-greedy versions of the previous three special characters.    {m,n}    Matches from m to n repetitions of the preceding RE.    {m,n}?   Non-greedy version of the above.    "\\"     Either escapes special characters or signals a special sequence.    []       Indicates a set of characters.             A "^" as the first character indicates a complementing set.    "|"      A|B, creates an RE that will match either A or B.    (...)    Matches the RE inside the parentheses.             The contents can be retrieved or matched later in the string.    (?iLmsux) Set the I, L, M, S, U, or X flag for the RE (see below).    (?:...)  Non-grouping version of regular parentheses.    (?P<name>...) The substring matched by the group is accessible by name.    (?P=name)     Matches the text matched earlier by the group named name.    (?#...)  A comment; ignored.    (?=...)  Matches if ... matches next, but doesn't consume the string.    (?!...)  Matches if ... doesn't match next.    (?<=...) Matches if preceded by ... (must be fixed length).    (?<!...) Matches if not preceded by ... (must be fixed length).    (?(id/name)yes|no) Matches yes pattern if the group with id/name matched,                       the (optional) no pattern otherwise.The special sequences consist of "\\" and a character from the listbelow.  If the ordinary character is not on the list, then theresulting RE will match the second character.    \number  Matches the contents of the group of the same number.    \A       Matches only at the start of the string.    \Z       Matches only at the end of the string.    \b       Matches the empty string, but only at the start or end of a word.    \B       Matches the empty string, but not at the start or end of a word.    \d       Matches any decimal digit; equivalent to the set [0-9].    \D       Matches any non-digit character; equivalent to the set [^0-9].    \s       Matches any whitespace character; equivalent to [ \t\n\r\f\v].    \S       Matches any non-whitespace character; equiv. to [^ \t\n\r\f\v].    \w       Matches any alphanumeric character; equivalent to [a-zA-Z0-9_].             With LOCALE, it will match the set [0-9_] plus characters defined             as letters for the current locale.    \W       Matches the complement of \w.    \\       Matches a literal backslash.This module exports the following functions:    match    Match a regular expression pattern to the beginning of a string.    search   Search a string for the presence of a pattern.    sub      Substitute occurrences of a pattern found in a string.    subn     Same as sub, but also return the number of substitutions made.    split    Split a string by the occurrences of a pattern.    findall  Find all occurrences of a pattern in a string.    finditer Return an iterator yielding a match object for each match.    compile  Compile a pattern into a RegexObject.    purge    Clear the regular expression cache.    escape   Backslash all non-alphanumerics in a string.Some of the functions in this module takes flags as optional parameters:    I  IGNORECASE  Perform case-insensitive matching.    L  LOCALE      Make \w, \W, \b, \B, dependent on the current locale.    M  MULTILINE   "^" matches the beginning of lines (after a newline)                   as well as the string.                   "$" matches the end of lines (before a newline) as well                   as the end of the string.    S  DOTALL      "." matches any character at all, including the newline.    X  VERBOSE     Ignore whitespace and comments for nicer looking RE's.    U  UNICODE     Make \w, \W, \b, \B, dependent on the Unicode locale.
#!/usr/bin/python# -*- coding: utf-8 -*-'''Python里数量词默认是贪婪的(在少数语言里也可能是默认非贪婪),总是尝试匹配尽可能多的字符;                   非贪婪的则相反,总是尝试匹配尽可能少的字符.例如:正则表达式"ab*"如果用于查找"abbbc",将找到"abbb";如果使用非贪婪的数量词"ab*?",将找到"a".'''from re import *def fun1():    '''一般字符'''    a = 'abc bbc\n cbc'    print findall(r'.',a)    print findall(r'\.','%s.'%a)    print findall(r'[ac]',a)    a = '^-]acbde'    print findall(r'[^ac]',a)                               #除了a,c以外的任意字符    print findall(r'[\^ac]',a)                              #^,a,c中的字符    print findall(r'[a^\-\]c]',a)                           #a,^,-.],c中的字符def fun2():    '''预定义字符集(可以用于字符集[...]中)'''    print findall(r'a\dc','a1c'),findall(r'a\dc','a c')     #\d数字字符    print findall(r'a\Dc','a1c'),findall(r'a\Dc','a c')     #\D非数字字符,等价于[^\d]    print findall(r'a\sc','a1c'),findall(r'a\sc','a c')     #\s,空白字符,等价于[空格,\t,\r,\n,\f,\v]    print findall(r'a\Sc','a1c'),findall(r'a\Sc','a c')     #\S,非空白字符,等价于[^\s]    print findall(r'a\wc','a1c'),findall(r'a\wc','a c')     #\w,单词字符,[a-z,A-Z,0-9]    print findall(r'a\Wc','a1c'),findall(r'a\Wc','a c')     #\W,非单词字符,[^\w]def fun3():    '''数量词(用于字符或(...)之后)'''    #'贪婪模式'    print findall(r'abc*','ab'),findall(r'abc*','abcc')     #匹配前一个字符0或无限次    print findall(r'abc+','ab'),findall(r'abc+','abcc')     #匹配前一个字符1或无限次    print findall(r'abc?','ab'),findall(r'abc?','abcc')     #匹配前一个字符0或1次    print findall(r'ab{2}','ab'),findall(r'ab{2}','abb')    #匹配前一个字符m次,由{m}中的m决定    print findall(r'ab{1,2}','ab')                          #匹配前一个字符m~n次,由{m,n}决定,m <= n    print findall(r'ab{1,2}','abbb')    #'非贪婪模式'    print findall(r'abc*?','abcc')                          #匹配前一个字符0或无限次,匹配尽可能少的字符    print findall(r'abc+?','abcc')                          #匹配前一个字符1或无限次,匹配尽可能少的字符    print findall(r'abc??','abcc')                          #匹配前一个字符0或1次,匹配尽可能少的字符    print findall(r'ab{1,2}?','abbb')                       #匹配前一个字符m~n次,匹配尽可能少的字符 def fun4():    '''边界匹配,不消耗匹配字符串中的字符'''    print findall(r'^a.*','ab'),findall(r'^a.*','cb')       #匹配字符串开头,在多行模式中匹配每一行的开头    print findall(r'ab$','ab'),findall(r'ab$','ac')         #匹配字符串末尾,在多行模式中匹配每一行的末尾    print findall(r'\Aab','abc'),findall(r'\Aab','acc')     #仅匹配字符串开头    print findall(r'ab\Z','cab'),findall(r'ab\Z','cbb')     #仅匹配字符串末尾    print findall(r'\bc','c bc c')                          #Matches the empty string, but only at the start or end of a word    print findall(r'a\Bbc','abc')                           #Matches the empty string, but not at the start or end of a worddef fun5():    '''逻辑与分组(分组的操作)'''    print findall(r'ab|cd','ab'),findall(r'ab|cd','cd')     #匹配|左右表达式中的任一个,总是先匹配左边的表达式,成功后跳过右边的表达式    print findall(r'(\w)','a~a')                            #被括起来的表达式将作为分组,第一个分组为1,每遇到一个'(',编号加1.                                                            #另外分组表达式作为一个整体,可以后接数量词.表达式中的|仅在该组中有效    print findall(r'(\w)\1','aabb')                         #\number,引用编号为number的分组匹配到的字符串    print findall(r'(\w)\1','aabc')    print findall(r'(?P<name1>\w)(?P=name1)','aabb')        #(?P<name>),给编号为n的分组指定别名(name),与使用编号等价    print findall(r'(?P<name1>\w)(?P=name1)','aabc')        #(?P=name),引用别名为name的分组匹配到的字符串def fun6():    '''特殊构造,不作为分组(不会分组的操作)'''    print findall(r'(?:\d)','a1b2')                         #匹配()中的正则表达式,但是不分组,没有编号    print findall(r'(?i)ab','Ab')                           #?iLmsux,每个字符代表一个匹配模式,只能用在正则表达式的开头,可选多个    print findall(r'a(?#explain)b','abab')                  #(?#...),#后面的内容将作为注释被忽略    print findall(r'a(?=\w)','a~aaa')                       #(?=...),之后的字符串内容需要匹配表达式才能成功匹配,不消耗字符串内容    print findall(r'a(?!\w)','a~aab')                       #(?!...),之后的字符串内容需要不匹配表达式才能成功匹配,不消耗字符串内容    print findall(r'(?<=\w)\w','a~aab')                     #(?<=...),之前的字符串内容需要匹配表达式才能成功匹配,不消耗字符串内容    print findall(r'(?<!\w)\w','a~aab')                     #(?<!...),之前的字符串内容需要不匹配表达式才能成功匹配,不消耗字符串内容    s = match(r'(a)?(?(1)b|c)', 'ab')                       #(?(id/name)yes|no),Matches yes pattern if the group with id/name matched,the (optional) no pattern otherwise.    print s.group()    s = match(r'(a)?(?(1)b|c)', 'c')                        #如果id/name的表达式匹配成功,则匹配yes表达式,否则匹配no表达式,no表达式为可选参数    print s.group()    s = match(r'(\d)?abc(?(1)yes|no)','1abcyes')    print s.group(),s.group(1)    print s.groups()    s = match(r'(\d)?abc(?(1)yes|no)','abcno')    print s.group(0),s.group(1)    print s.groups()

re

re.compile

compile(pattern, flags=0)    Compile a regular expression pattern, returning a pattern object.

Pattern类的工厂方法,将字符串形式的正则表达式编译为Pattern对象。可以把那些经常使用的正则表达式编译成正则表达式对象,可以提高一定的效率。

pattern,正则表达式

flags,匹配模式,可选值为

  1. re.I(re.IGNORECASE = 2):忽略大小写(括号内是完整写法与相应的值,下同),

  2. re.M(MULTILINE = 8):多行模式

  3. re.S(DOTALL = 16):改变.的行为,匹配换行符

  4. re.L(LOCALE = 4):使预定字符类 \w \W \b \B \s \S 取决于当前区域设定

  5. re.U(UNICODE = 32):使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性

  6. re.X(VERBOSE = 64):这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释。以下两个正则表达式等价

    a = re.compile(r"""\d +  # the integral part\.    # the decimal point\d *  # some fractional digits""", re.X)b = re.compile(r"\d+\.\d*")print a.findall('11.11')   #['11.11']print b.findall('11.11')   #['11.11']

re的方法

  1. findall(pattern, string, flags=0) -> list

    返回能与pattern匹配的全部子串

    pattern,正则表达式

    string,要匹配的字符串

    flags,匹配模式

    print re.findall(r'[a,b]','a1b2A3')       #['a', 'b']print re.findall(r'[a,b]','a1b2A3',re.I)  #['a', 'b', 'A']
  2. finditer(pattern, string, flags=0)

    返回一个顺序访问每一个匹配结果的迭代器,迭代器返回的是Match对象

    for i in re.finditer(r'[a,b]','a1b2c3'):       print i.group()                   #a,b
  3. match(pattern, string, flags=0)

    从string**开始匹配**pattern,如果pattern成功匹配,则返回一个Match对象;如果pattern无法匹配,则返回None

    m = re.match(r'([a,b])','a1b2A3')if m:   print m.group()                       #a   print m.group(1)                      #a
  4. search(pattern, string, flags=0)

    在字符串中找到第一个匹配项后立即返回一个Match对象;如果字符串中没有匹配项,返回None

    m = re.search(r'([a,b])','a1b2A3')if m:   print m.group()                       #a   print m.group(1)                      #am = re.search(r'([a,b])','b1b2A3')if m:   print m.group()                       #b   print m.group(1)                      #b
  5. split(pattern, string, maxsplit=0, flags=0) -> list

    按照pattern分割string

    print re.split(r'([a,b])','a1b2A3')       #['', 'a', '1', 'b', '2A3']
  6. sub(pattern, repl, string, count=0, flags=0) -> str

    使用repl替换string中每一个匹配成功的子串,返回替换后的字符串

    • 当repl是一个字符串时,可以使用\id,\g<id>,\g<name>引用分组,但不能使用编号0。
    • 当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)

    count用于指定最多替换次数,不指定时全部替换。

    print re.sub(r'([a,b])','xx','a1b2A3')    #xx1xx2A3def func(m):   return m.group(1) + 'x'print re.sub(r'([a,b])',func,'a1b2A3')    #ax1bx2A3
  7. subn(pattern, repl, string, count=0, flags=0) -> (sub(pattern,repl,string,count,flags),替换次数)

    print re.subn(r'([a,b])','xx','a1b2A3')   #('xx1xx2A3', 2)def func(m):   return m.group(1) + 'x'print re.subn(r'([a,b])',func,'a1b2A3')   #('xx1xx2A3', 2)
  8. escape(pattern)

    转义,一般来说没啥用…

    >>> s1 = ".+\d123">>> s2 = r".+\d123">>> re.escape(s1)                       '\\.\\+\\\\d123'>>> re.escape(s2)                       '\\.\\+\\\\d123'

Match对象

import rem = re.match(r'(\w+) (\w+)(?P<name1>.)(?P<name2>.)', 'hello world!?')
  1. string:匹配时使用的文本

  2. re: 匹配时使用的Pattern对象

  3. pos: 文本中正则表达式开始搜索的索引

  4. endpos: 文本中正则表达式结束搜索的索引

  5. lastindex: 最后一个被捕获的分组在文本中的索引。如果没有被捕获的分组,将为None

  6. lastgroup: 最后一个被捕获的分组的别名。如果这个分组没有别名或者没有被捕获的分组,将为None

    print "m.string:", m.string        #m.string: hello world!?print "m.re:", m.re                #m.re: <_sre.SRE_Pattern object at 0x0000000002F98580>print "m.pos:", m.pos              #m.pos: 0print "m.endpos:", m.endpos        #m.endpos: 13print "m.lastindex:", m.lastindex  #m.lastindex: 4print "m.lastgroup:", m.lastgroup  #m.lastgroup: name2
  7. group([group1, ...]) -> str or tuple.

    获得一个或多个分组截获的字符串;指定多个参数时将以元组形式返回。

    group1可以使用编号也可以使用别名;编号0代表整个匹配的子串;不填写参数时,返回group(0);没有截获字符串的组返回None;截获了多次的组返回最后一次截获的子串。

    使用编号时需要注意,如果正则表达式中的编号至n,group1 应<= n

    print "m.group(0):", m.group(0)                     #m.group(0): hello world!?print "m.group(1,2):", m.group(1,2)                 #m.group(1,2): ('hello', 'world')print "m.group(1,2,3):", m.group(1,2,3)             #m.group(1,2,3): ('hello', 'world', '!')print "m.group(1,2,3,4):", m.group(1,2,3,4)         #m.group(1,2,3,4): ('hello', 'world', '!', '?')try:   print "m.group(1,2,3,4,5):", m.group(1,2,3,4,5) #m.group(1,2,3,4,5): no such groupexcept Exception,e:   print etest = re.match(r'\d(\w)\d','123')print test.group(1)                                 #'2',返回编号为1的分组print test.group()                                  #'123',默认返回group(0),代表整个匹配的子串
  8. groups([default=None]) -> tuple.

    以元组形式返回全部分组截获的字符串,相当于调用group(1,2,…last)

    default表示没有截获字符串的组以这个值替代

    #本例中与m.group(1,2,3,4)等价print "m.groups():", m.groups()                     #m.groups(): ('hello', 'world', '!', '?')
  9. groupdict([default=None]) -> dict.

    返回以有别名的组的别名为键、以该组截获的子串为值的字典,没有别名的组不包含在内

    default表示没有截获字符串的组以这个值替代

    print "m.groupdict():", m.groupdict()               #m.groupdict(): {'name2': '?', 'name1': '!'}
  10. start([group=0]) -> int.

    返回指定的组截获的子串在string中的起始索引(子串第一个字符的索引)。group默认值为0。

    print "m.start(2):", m.start(2)                     #m.start(2): 6,分组2(hello)的开始索引print "m.start(name1):",m.start('name1')            #m.start(name1): 11,分组名为name1(!)的开始索引print "m.start(name2):",m.start('name2')            #m.start(name2): 12,分组名为name2(?)的开始索引
  11. end([group=0]) -> int.

    返回指定的组截获的子串在string中的结束索引(子串最后一个字符的索引+1)

    print "m.end(2):", m.end(2)                         #m.end(2): 11,分组2(hello)结束索引 + 1print "m.end(name1):",m.end('name1')                #m.end(name1): 12,分组名为name1(!)的结束索引 + 1print "m.end(name2):",m.end('name2')                #m.end(name2): 13,分组名为name2(!)的结束索引 + 1
  12. span([group]) -> (m.start(group), m.end(group))

    s = 'hello world!?'                                 span = m.span(2)                                    print "m.span(2):", span                            #m.span(2): (6, 11)print s[span[0]:span[1]]                            #world
  13. expand(template) -> str.

    将匹配到的分组代入template中然后返回。template中可以使用\id,\g<id>,\g<name>引用分组,但不能使用编号0。\id与\g<id>是等价的;但\10将被认为是第10个分组,如果想表达\1之后是字符’0’,只能使用\g<1>0

    print m.expand(r'\2 \1\3')                          #world hello!print m.expand(r'\g<name1>,\g<name2>,\g<2>')        #!,?,world

Pattern对象

import repat = re.compile(r'\d')
  1. findall(string[, pos[, endpos]]) --> list.

    返回能与pattern匹配的全部子串

    pos,string开始匹配的下标

    endpos,string结束匹配的下标

    pat.findall('a1b2c3')      #['1', '2', '3']
  2. finditer(string[, pos[, endpos]]) --> iterator.

    返回一个顺序访问每一个匹配结果的迭代器,迭代器返回的是Match对象

    for i in pat.finditer('a1b2c3'):       print i.group()    #1,2,3
  3. match(string[, pos[, endpos]]) --> match object or None.

    从string的pos下标起匹配pattern;如果成功匹配,立即返回一个Match对象;如果无法匹配,则返回None
    pos和endpos的默认值分别为0和len(string)

    m = pat.match('a1b2c3')    #m为None,因为从下标0开始匹配,未成功匹配if m:                      print m.group()m = pat.match('a1b2c3',1)  #从下标1开始匹配,成功匹配if m:   print m.group()        #1
  4. search(string[, pos[, endpos]]) --> match object or None.

    用于查找字符串中可以匹配成功的子串。

    从string的pos下标处起尝试匹配pattern,如果pattern匹配成功,立即返回一个Match对象;若无法匹配,则将pos加1后重新尝试匹配;直到pos = endpos时仍无法匹配,则返回None。

    pos和endpos的默认值分别为0和len(string))

    可以认为search为固执版的match,不到结尾不死心,一旦匹配成功立马返回

    m = pat.search('a1b2c3')if m:   print m.group()       #1
  5. split(string[, maxsplit = 0]) --> list.

    按照能够匹配的子串将string分割

    maxsplit用于指定最大分割次数,不指定将全部分割。

    pat.split('a1b2c3')       #['a', 'b', 'c', '']
  6. sub(repl, string[, count = 0]) --> newstring

    使用repl替换string中每一个匹配的子串,返回替换后的字符串。

    • 当repl是一个字符串时,可以使用\id\g<id>\g<name>引用分组,但不能使用编号0。
    • 当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。

    count用于指定最多替换次数,不指定时全部替换。

    func = lambda x:x.group(0) + 'x'   print pat.sub('x','a1b2c3')        #axbxcxprint pat.sub(func,'a1b2c3')       #a1xb2xc3x
  7. subn(repl, string[, count = 0]) --> (sub(repl, string[, count]), 替换次数)

    func = lambda x:x.group(0) + 'x'   print pat.subn('x','a1b2c3')       #('axbxcx', 3)print pat.subn(func,'a1b2c3')      #('a1xb2xc3x', 3)
  8. pattern:编译时用的表达式字符串

  9. flags:编译时用的匹配模式(数字形式)

  10. groups:表达式中分组的数量

  11. groupindex:以表达式中有别名的组的别名为键、以该组对应的编号为值的字典,没有别名的组不包含在内

    print pat.pattern       #\dprint pat.flags         #0print pat.groups        #0print pat.groupindex    #{} 

请尊重作者的劳动,转载请注明作者及原文地址(http://blog.csdn.net/lis_12/article/details/54691455).

如果觉得本文对您有帮助,请点击‘顶’支持一下,您的支持是我写作最大的动力,谢谢。

参考网址

  1. https://docs.python.org/2/library/re.html#module-re
  2. http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html
0 0
原创粉丝点击