首頁  >  文章  >  後端開發  >  Python 正規表示式

Python 正規表示式

黄舟
黄舟原創
2017-02-04 16:34:161205瀏覽

簡介

正規表示式(regular expression)是可以匹配文字片段的模式。最簡單的正規表示式就是普通字串,可以符合其自身。例如,正規表示式 ‘hello’ 可以符合字串 ‘hello’。

要注意的是,正規表示式並不是一個程序,而是用於處理字串的一種模式,如果你想用它來處理字串,就必須使用支援正規表示式的工具,例如Linux 中的 awk, sed, grep,或程式語言 Perl, Python, Java 等等。

正規表示式有多種不同的風格,下表列出了適用於Python 或Perl 等程式語言的部分元字元以及說明:

Python 正規表示式

re 模組

在Pytyt 中,我們可以使用Pyt內建的re 模組來使用正規表示式。

有一點需要特別注意的是,正規表示式使用 對特殊字元進行轉義,例如,為了匹配字串 'python.org',我們需要使用正規表示式 'python.org',而 Python 的字串本身也用 轉義,所以上面的正規表示式在 Python 中應該寫成 'python.org',這會很容易陷入 的困擾中,因此,我們建議使用Python 的原始字串,只需加一個r 前綴,上面的正則表達式可以寫成:

r'python\.org'

re 模組提供了不少有用的函數,用以匹配字串,例如:

  • compile 函數

  • match 函數

  • search 函數

  • findall 函數

    search 函數
  • sub 函數

  • subn 函數

  • re 模組的一般使用步驟如下:

使用compile 函數將正規表示式的字串形式編譯為一個Pattern 物件

  • 透過Pattern 物件提供的一系列方法對文字進行比對匹配結果(一個Match 物件)

  • 最後使用Match 物件提供的屬性和方法獲得信息,根據需要進行其他的操作

  • compile 函數

  • ,函數用於Pattern 對象,它的一般使用形式如下:

    re.compile(pattern[, 
    flag])
  • 其中,pattern 是一個字串形式的正規表示式,flag 是一個可選參數,表示匹配模式,例如忽略大小寫,多行模式等。

下面,讓我們來看看例子。

import re
 
# 
将正则表达式编译成 Pattern 对象 
pattern = re.compile(r'\d+')

在上面,我們已將一個正規表示式編譯成 Pattern 對象,接下來,我們就可以利用 pattern 的一系列方法對文本進行匹配查找了。 Pattern 物件的一些常用方法主要有:

match 方法

  • search 方法

  • findall 方法

  • sub 方法

  • subn 方法

  • match 方法

  • match 方法用於查找字串的頭部(也可以指定起始位置),它是一次匹配,只要找到了一個匹配的結果就返回,而不是查找所有匹配的結果。它的一般使用形式如下:

    match(string[, pos[, 
    endpos]])

    其中,string 是待匹配的字串,pos 和 endpos 是可選參數,指定字串的起始和終點位置,預設值分別是 0 和 len (字串長度)。因此,當你不指定 pos 和 endpos 時,match 方法預設符合字串的頭部。
  • 當匹配成功時,返回一個 Match 對象,如果沒有匹配上,則返回 None。

    看看範例。
  • >>> import re
    >>> pattern = re.compile(r'\d+')                    # 用于匹配至少一个数字
    >>> m = pattern.match('one12twothree34four')        # 查找头部,没有匹配
    >>> print m
    None
    >>> m = pattern.match('one12twothree34four', 2, 10) # 从'e'的位置开始匹配,没有匹配
    >>> print m
    None
    >>> m = pattern.match('one12twothree34four', 3, 10) # 从'1'的位置开始匹配,正好匹配
    >>> print m                                         # 返回一个 Match 对象
    <_sre.SRE_Match object at 0x10a42aac0>
    >>> m.group(0)   # 可省略 0
    &#39;12&#39;
    >>> m.start(0)   # 可省略 0
    3
    >>> m.end(0)     # 可省略 0
    5
    >>> m.span(0)    # 可省略 0
    (3, 5)
  • 在上面,當匹配成功時返回一個Match 對象,其中:

group([group1, …]) 方法用於獲得一個或多個分組匹配的字符串,當要獲得整個匹配的子串時,可直接使用group() 或 group(0);

start([group]) 方法用於取得分組匹配的子字串在整個字串中的起始位置(子字串第一個字元的索引),參數預設值為0;

end([group]) 方法用於取得分組匹配的子字串在整個字串中的結束位置(子字串最後一個字元的索引+1),參數預設值為0;

  • span ([group]) 方法回傳(start(group), end(group))。

  • 再看看一個例子:

    >>> import re
    >>> pattern = re.compile(r&#39;([a-z]+) ([a-z]+)&#39;, re.I)   # re.I 表示忽略大小写
    >>> m = pattern.match(&#39;Hello World Wide Web&#39;)
    >>> print m                               # 匹配成功,返回一个 Match 对象
    <_sre.SRE_Match object at 0x10bea83e8>
    >>> m.group(0)                            # 返回匹配成功的整个子串
    &#39;Hello 
    World&#39;
    >>> m.span(0)                             # 返回匹配成功的整个子串的索引
    (0, 11)
    >>> m.group(1)                            # 返回第一个分组匹配成功的子串
    &#39;Hello&#39;
    >>> m.span(1)                             # 返回第一个分组匹配成功的子串的索引
    (0, 5)
    >>> m.group(2)                            # 返回第二个分组匹配成功的子串
    &#39;World&#39;
    >>> m.span(2)                             # 返回第二个分组匹配成功的子串
    (6, 11)
    >>> m.groups()                            # 等价于 (m.group(1), m.group(2), ...)
    (&#39;Hello&#39;, &#39;World&#39;)
    >>> m.group(3)                            # 不存在第三个分组
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: no such group

  • search 方法
  • search 方法用於查找字符串的任何位置,它也是一次匹配,只要找到了一個匹配的結果就返回,而不是查找所有匹配的結果,它的一般使用形式如下:
  • search(string[, pos[, 
    endpos]])
  • 其中,string 是待匹配的字串,pos 和endpos 是可選參數,指定字串的起始和終點位置,預設值分別是0 和len (字符串長度)。

    当匹配成功时,返回一个 Match 对象,如果没有匹配上,则返回 None。

    让我们看看例子:

    >>> import re
    >>> pattern = re.compile(&#39;\d+&#39;)
    >>> m = pattern.search(&#39;one12twothree34four&#39;)  # 这里如果使用 match 方法则不匹配
    >>> m
    <_sre.SRE_Match object at 0x10cc03ac0>
    >>> m.group()
    &#39;12&#39;
    >>> m = pattern.search(&#39;one12twothree34four&#39;, 10, 30)  # 指定字符串区间
    >>> m
    <_sre.SRE_Match object at 0x10cc03b28>
    >>> m.group()
    &#39;34&#39;
    >>> m.span()
    (13, 15)

    再来看一个例子:

    # 
    -*- coding: utf-8 -*-
     
    import re
    # 
    将正则表达式编译成 Pattern 对象
    pattern = re.compile(r&#39;\d+&#39;) 
    # 
    使用 search() 查找匹配的子串,不存在匹配的子串时将返回 None 
    # 
    这里使用 match() 无法成功匹配 
    m = pattern.search(&#39;hello 123456 789&#39;) 
    if m: 
        # 使用 Match 获得分组信息 
        print &#39;matching string:&#39;,m.group()
        print &#39;position:&#39;,m.span()

    执行结果:

    matching string: 123456
    position: (6, 12)

    findall 方法

    上面的 match 和 search 方法都是一次匹配,只要找到了一个匹配的结果就返回。然而,在大多数时候,我们需要搜索整个字符串,获得所有匹配的结果。

    findall 方法的使用形式如下:

    findall(string[, pos[, 
    endpos]])

    其中,string 是待匹配的字符串,pos 和 endpos 是可选参数,指定字符串的起始和终点位置,默认值分别是 0 和 len (字符串长度)。

    findall 以列表形式返回全部能匹配的子串,如果没有匹配,则返回一个空列表。

    看看例子:

    import 
    re
    pattern = re.compile(r&#39;\d+&#39;)   # 查找数字
    result1 = pattern.findall(&#39;hello 123456 789&#39;)
    result2 = pattern.findall(&#39;one1two2three3four4&#39;, 0, 10)
    print 
    result1
    print result2

    执行结果:

    [&#39;123456&#39;, &#39;789&#39;]
    [&#39;1&#39;, &#39;2&#39;]

    finditer 方法

    finditer 方法的行为跟 findall 的行为类似,也是搜索整个字符串,获得所有匹配的结果。但它返回一个顺序访问每一个匹配结果(Match 对象)的迭代器。

    看看例子:

    # 
    -*- coding: utf-8 -*-
     
    import 
    re
    pattern = re.compile(r&#39;\d+&#39;)
     
    result_iter1 = pattern.finditer(&#39;hello 123456 789&#39;)
    result_iter2 = pattern.finditer(&#39;one1two2three3four4&#39;, 0, 10)
     
    print type(result_iter1)
    print type(result_iter2)
     
    print &#39;result1...&#39;
    for m1 in result_iter1:   # m1 是 Match 对象
        print &#39;matching string: {}, position: {}&#39;.format(m1.group(), m1.span())
     
    print &#39;result2...&#39;
    for m2 in result_iter2:
        print &#39;matching string: {}, position: {}&#39;.format(m2.group(), m2.span())

    执行结果:

    <type &#39;callable-iterator&#39;>
    <type &#39;callable-iterator&#39;>
    result1...
    matching string: 123456, position: (6, 12)
    matching string: 789, position: (13, 16)
    result2...
    matching string: 1, position: (3, 4)
    matching string: 2, position: (7, 8)

    split 方法

    split 方法按照能够匹配的子串将字符串分割后返回列表,它的使用形式如下:

    split(string[, 
    maxsplit])

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

    看看例子:

    import re
    p = re.compile(r&#39;[\s\,\;]+&#39;)
    print p.split(&#39;a,b;; c   d&#39;

    执行结果:

    [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, 
    &#39;d&#39;]

    sub 方法

    sub 方法用于替换。它的使用形式如下:

    sub(repl, string[, 
    count])

    其中,repl 可以是字符串也可以是一个函数:

    • 如果 repl 是字符串,则会使用 repl 去替换字符串每一个匹配的子串,并返回替换后的字符串,另外,repl 还可以使用 id 的形式来引用分组,但不能使用编号 0;

    • 如果 repl 是函数,这个方法应当只接受一个参数(Match 对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。

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

    看看例子:

    import re
    p = re.compile(r&#39;(\w+) (\w+)&#39;)
    s = &#39;hello 123, hello 456&#39;
     
    def func(m):
        return &#39;hi&#39; + &#39; &#39; + m.group(2)
     
    print p.sub(r&#39;hello world&#39;, s)  # 使用 &#39;hello world&#39; 替换 &#39;hello 123&#39; 和 &#39;hello 456&#39;
    print p.sub(r&#39;\2 \1&#39;, s)        # 引用分组
    print p.sub(func, s)
    print p.sub(func, s, 1)         # 最多替换一次

    执行结果:

    hello world, hello world
    123 hello, 456 hello
    hi 123, hi 456
    hi 123, hello 456

    subn 方法

    subn 方法跟 sub 方法的行为类似,也用于替换。它的使用形式如下:

    subn(repl, string[, 
    count])

    它返回一个元组:

    (sub(repl, string[, 
    count]), 替换次数)

    元组有两个元素,第一个元素是使用 sub 方法的结果,第二个元素返回原字符串被替换的次数。

    看看例子:

    import re
    p = re.compile(r&#39;(\w+) (\w+)&#39;)
    s = &#39;hello 123, hello 456&#39;
     
    def func(m):
        return &#39;hi&#39; + &#39; &#39; + m.group(2)
     
    print p.subn(r&#39;hello world&#39;, s)
    print p.subn(r&#39;\2 \1&#39;, s)
    print p.subn(func, s)
    print p.subn(func, s, 1)

    执行结果:

    (&#39;hello world, hello world&#39;, 2)
    (&#39;123 hello, 456 hello&#39;, 2)
    (&#39;hi 123, hi 456&#39;, 2)
    (&#39;hi 123, hello 456&#39;, 1)

    其他函数

    事实上,使用 compile 函数生成的 Pattern 对象的一系列方法跟 re 模块的多数函数是对应的,但在使用上有细微差别。

    match 函数

    match 函数的使用形式如下:

    re.match(pattern, 
    string[, flags]):

    其中,pattern 是正则表达式的字符串形式,比如 d+, [a-z]+。

    而 Pattern 对象的 match 方法使用形式是:

    match(string[, pos[, 
    endpos]])

    可以看到,match 函数不能指定字符串的区间,它只能搜索头部,看看例子:

    import re
     
    m1 = re.match(r&#39;\d+&#39;, &#39;One12twothree34four&#39;)
    if m1:
        print &#39;matching string:&#39;,m1.group()
    else:
        print &#39;m1 is:&#39;,m1
        
    m2 = re.match(r&#39;\d+&#39;, &#39;12twothree34four&#39;)
    if m2:
        print &#39;matching string:&#39;, m2.group()
    else:
        print &#39;m2 is:&#39;,m2

    执行结果:

    m1 is: None
    matching string: 12

    search 函数

    search 函数的使用形式如下:

    re.search(pattern, 
    string[, flags])

    search 函数不能指定字符串的搜索区间,用法跟 Pattern 对象的 search 方法类似。

    findall 函数

    findall 函数的使用形式如下:

    re.findall(pattern, 
    string[, flags])

    findall 函数不能指定字符串的搜索区间,用法跟 Pattern 对象的 findall 方法类似。

    看看例子:

    import 
    re
     
    print re.findall(r&#39;\d+&#39;, &#39;hello 12345 789&#39;)
     
    # 
    输出
    [&#39;12345&#39;, &#39;789&#39;]

    finditer 函数

    finditer 函数的使用方法跟 Pattern 的 finditer 方法类似,形式如下:

    re.finditer(pattern, 
    string[, flags])

    split 函数

    split 函数的使用形式如下:

    re.split(pattern, 
    string[, maxsplit])

    sub 函数

    sub 函数的使用形式如下:

    re.sub(pattern, repl, 
    string[, count])

    subn 函数

    subn 函数的使用形式如下:

    re.subn(pattern, repl, 
    string[, count])

    到底用哪种方式

    从上文可以看到,使用 re 模块有两种方式:

    • 使用 re.compile 函数生成一个 Pattern 对象,然后使用 Pattern 对象的一系列方法对文本进行匹配查找;

    • 直接使用 re.match, re.search 和 re.findall 等函数直接对文本匹配查找;

    下面,我们用一个例子展示这两种方法。

    先看第 1 种用法:

    import re
     
    # 
    将正则表达式先编译成 Pattern 对象
    pattern = re.compile(r&#39;\d+&#39;)
     
    print pattern.match(&#39;123, 123&#39;)
    print pattern.search(&#39;234, 234&#39;)
    print pattern.findall(&#39;345, 345&#39;)

    再看第 2 种用法:

    import 
    re
     
    print re.match(r&#39;\d+&#39;, &#39;123, 123&#39;)
    print re.search(r&#39;\d+&#39;, &#39;234, 234&#39;)
    print re.findall(r&#39;\d+&#39;, &#39;345, 345&#39;)

    如果一个正则表达式需要用到多次(比如上面的 d+),在多种场合经常需要被用到,出于效率的考虑,我们应该预先编译该正则表达式,生成一个 Pattern 对象,再使用该对象的一系列方法对需要匹配的文件进行匹配;而如果直接使用 re.match, re.search 等函数,每次传入一个正则表达式,它都会被编译一次,效率就会大打折扣。

    因此,我们推荐使用第 1 种用法。

    匹配中文

    在某些情况下,我们想匹配文本中的汉字,有一点需要注意的是,中文的 unicode 编码范围 主要在 [u4e00-u9fa5],这里说主要是因为这个范围并不完整,比如没有包括全角(中文)标点,不过,在大部分情况下,应该是够用的。

    假设现在想把字符串 title = u'你好,hello,世界' 中的中文提取出来,可以这么做:

    # 
    -*- coding: utf-8 -*-
     
    import 
    re
     
    title = u&#39;你好,hello,世界&#39;
    pattern = re.compile(ur&#39;[\u4e00-\u9fa5]+&#39;)
    result = pattern.findall(title)
     
    print result

    注意到,我们在正则表达式前面加上了两个前缀 ur,其中 r 表示使用原始字符串,u 表示是 unicode 字符串。

    执行结果:

    [u&#39;\u4f60\u597d&#39;, 
    u&#39;\u4e16\u754c&#39;]

    贪婪匹配

    在 Python 中,正则匹配默认是贪婪匹配(在少数语言中可能是非贪婪),也就是匹配尽可能多的字符。

    比如,我们想找出字符串中的所有 div 块:

    import re
     
    content = &#39;aa<div>test1</div>bb<div>test2</div>cc&#39;
    pattern = re.compile(r&#39;<div>.*</div>&#39;)
    result = pattern.findall(content)
     
    print result

    执行结果:

    [&#39;<div>test1</div>bb<div>test2</div>&#39;]

    由于正则匹配是贪婪匹配,也就是尽可能多的匹配,因此,在成功匹配到第一个

    时,它还会向右尝试匹配,查看是否还有更长的可以成功匹配的子串。

    如果我们想非贪婪匹配,可以加一个 ?,如下:

    import re
     
    content = &#39;aa<div>test1</div>bb<div>test2</div>cc&#39;
    pattern = re.compile(r&#39;<div>.*?</div>&#39;)    # 加上 ?
    result = pattern.findall(content)
     
    print result

    结果:

    [&#39;<div>test1</div>&#39;, 
    &#39;<div>test2</div>&#39;]

    小结

    • re 模块的一般使用步骤如下:

    1. 使用 compile 函数将正则表达式的字符串形式编译为一个 Pattern 对象;

    2. 通过 Pattern 对象提供的一系列方法对文本进行匹配查找,获得匹配结果(一个 Match 对象);

    3. 最后使用 Match 对象提供的属性和方法获得信息,根据需要进行其他的操作;

    • Python 的正则匹配默认是贪婪匹配


    以上就是Python 正则表达式 的内容,更多相关内容请关注PHP中文网(www.php.cn)!


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn