1. 程式人生 > >Python正則表示式操作指南

Python正則表示式操作指南

 

原文作者:A.M. Kuchling ([email protected]

校對人員:Leal

適用版本:Python 1.5 及後續版本

文章狀態:校對階段

Abstract(摘要)

This document is an introductory tutorial to using regular expressions in Python with the re module. It provides a gentler introduction than the corresponding section in the Library Reference.
本文是通過Python的 re 模組來使用正則表示式的一個入門教程,和庫參考手冊的對應章節相比,更為淺顯易懂、循序漸進。

Contents(目錄)

Introduction(簡介)

The re module was added in Python 1.5, and provides Perl-style regular expression patterns. Earlier versions of Python came with the regex module, which provides Emacs-style patterns. Emacs-style patterns are slightly less readable and don't provide as many features, so there's not much reason to use the regex module when writing new code, though you might encounter old code that uses it.
Python 自1.5版本起增加了re 模組,它提供 Perl 風格的正則表示式模式。Python 1.5之前版本則是通過 regex 模組提供 Emecs 風格的模式。Emacs 風格模式可讀性稍差些,而且功能也不強,因此編寫新程式碼時儘量不要再使用 regex 模組,當然偶爾你還是可能在老程式碼裡發現其蹤影。

Regular expressions (or REs) are essentially a tiny, highly specialized programming language embedded inside Python and made available through the re module. Using this little language, you specify the rules for the set of possible strings that you want to match; this set might contain English sentences, or e-mail addresses, or TeX commands, or anything you like. You can then ask questions such as "Does this string match the pattern?", or "Is there a match for the pattern anywhere in this string?". You can also use REs to modify a string or to split it apart in various ways.
就其本質而言,正則表示式(或 RE)是一種小型的、高度專業化的程式語言,(在Python中)它內嵌在Python中,並通過 re 模組實現。使用這個小型語言,你可以為想要匹配的相應字串集指定規則;該字串集可能包含英文語句、e-mail地址、TeX命令或任何你想搞定的東西。然後你可以問諸如“這個字串匹配該模式嗎?”或“在這個字串中是否有部分匹配該模式呢?”。你也可以使用 RE 以各種方式來修改或分割字串。

Regular expression patterns are compiled into a series of bytecodes which are then executed by a matching engine written in C. For advanced use, it may be necessary to pay careful attention to how the engine will execute a given RE, and write the RE in a certain way in order to produce bytecode that runs faster. Optimization isn't covered in this document, because it requires that you have a good understanding of the matching engine's internals.
正則表示式模式被編譯成一系列的位元組碼,然後由用 C 編寫的匹配引擎執行。在高階用法中,也許還要仔細留意引擎是如何執行給定 RE ,如何以特定方式編寫 RE 以令生產的位元組碼執行速度更快。本文並不涉及優化,因為那要求你已充分掌握了匹配引擎的內部機制。

The regular expression language is relatively small and restricted, so not all possible string processing tasks can be done using regular expressions. There are also tasks that can be done with regular expressions, but the expressions turn out to be very complicated. In these cases, you may be better off writing Python code to do the processing; while Python code will be slower than an elaborate regular expression, it will also probably be more understandable.
正則表示式語言相對小型和受限(功能有限),因此並非所有字串處理都能用正則表示式完成。當然也有些任務可以用正則表示式完成,不過最終表示式會變得異常複雜。碰到這些情形時,編寫 Python 程式碼進行處理可能反而更好;儘管 Python 程式碼比一個精巧的正則表示式要慢些,但它更易理解。

Simple Patterns(簡單模式)

We'll start by learning about the simplest possible regular expressions. Since regular expressions are used to operate on strings, we'll begin with the most common task: matching characters.
我們將從最簡單的正則表示式學習開始。由於正則表示式常用於字串操作,那我們就從最常見的任務:字元匹配 下手。

For a detailed explanation of the computer science underlying regular expressions (deterministic and non-deterministic finite automata), you can refer to almost any textbook on writing compilers.
有關正則表示式底層的電腦科學上的詳細解釋(確定性和非確定性有限自動機),你可以查閱編寫編譯器相關的任何教科書。

1. Matching Characters(字元匹配)

Most letters and characters will simply match themselves. For example, the regular expression test will match the string "test" exactly. (You can enable a case-insensitive mode that would let this RE match "Test" or "TEST" as well; more about this later.)
大多數字母和字元一般都會和自身匹配。例如,正則表示式 test 會和字串“test”完全匹配。(你也可以使用大小寫不敏感模式,它還能讓這個 RE 匹配“Test”或“TEST”;稍後會有更多解釋。)

There are exceptions to this rule; some characters are special, and don't match themselves. Instead, they signal that some out-of-the-ordinary thing should be matched, or they affect other portions of the RE by repeating them. Much of this document is devoted to discussing various metacharacters and what they do.
這個規則當然會有例外;有些字元比較特殊,它們和自身並不匹配,而是會表明應和一些特殊的東西匹配,或者它們會影響到 RE 其它部分的重複次數。本文很大篇幅專門討論了各種元字元及其作用。

Here's a complete list of the metacharacters; their meanings will be discussed in the rest of this HOWTO.
這裡有一個元字元的完整列表;其含義會在本指南餘下部分進行討論。

. ^ $ * + ? { [ ] \ | ( )

The first metacharacters we'll look at are "[" and "]". They're used for specifying a character class, which is a set of characters that you wish to match. Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a "-". For example, [abc] will match any of the characters "a", "b", or "c"; this is the same as [a-c], which uses a range to express the same set of characters. If you wanted to match only lowercase letters, your RE would be [a-z].
我們首先考察的元字元是 "[" 和 "]"。它們常用來指定一個字元類別,所謂字元類別就是你想匹配的一個字符集。字元可以單個列出,也可以用“-”號分隔的兩個給定字元來表示一個字元區間。例如,[abc] 將匹配"a", "b", 或 "c"中的任意一個字元;也可以用區間[a-c]來表示同一字符集,和前者效果一致。如果你只想匹配小寫字母,那麼 RE 應寫成 [a-z]。

Metacharacters are not active inside classes. For example, [akm$] will match any of the characters "a", "k", "m", or "$"; "$" is usually a metacharacter, but inside a character class it's stripped of its special nature.
元字元在類別裡並不起作用。例如,[akm$]將匹配字元"a", "k", "m", 或 "$" 中的任意一個;"$"通常用作元字元,但在字元類別裡,其特性被除去,恢復成普通字元。

You can match the characters not within a range by complementing the set. This is indicated by including a "" as the first character of the class; `"" elsewhere will simply match the ""` character. For example, [5] will match any character except "5".
你可以用補集來匹配不在區間範圍內的字元。其做法是把"^"作為類別的首個字元;其它地方的"^"只會簡單匹配 "^" 字元本身。例如,[^5] 將匹配除 "5" 之外的任意字元。

Perhaps the most important metacharacter is the backslash, "\". As in Python string literals, the backslash can be followed by various characters to signal various special sequences. It's also used to escape all the metacharacters so you can still match them in patterns; for example, if you need to match a "[" or "\", you can precede them with a backslash to remove their special meaning: \[ or \\.
也許最重要的元字元是反斜槓"\"。 做為 Python 中的字串字母,反斜槓後面可以加不同的字元以表示不同特殊意義。它也可以用於取消所有的元字元,這樣你就可以在模式中匹配它們了。舉個例子,如果你需要匹配字元 "[" 或 "\",你可以在它們之前用反斜槓來取消它們的特殊意義: \[ 或 \\。

Some of the special sequences beginning with "\" represent predefined sets of characters that are often useful, such as the set of digits, the set of letters, or the set of anything that isn't whitespace. The following predefined special sequences are available:
一些用 "\" 開始的特殊字元所表示的預定義字符集通常是很有用的,象數字集,字母集,或其它非空字符集。下列是可用的預設特殊字元:

\d

  • Matches any decimal digit; this is equivalent to the class [0-9].
    匹配任何十進位制數;它相當於類 [0-9]。

\D

  • Matches any non-digit character; this is equivalent to the class [^0-9].
    匹配任何非數字字元;它相當於類 [^0-9]。

\s

  • Matches any whitespace character; this is equivalent to the class [ \t\n\r\f\v].
    匹配任何空白字元;它相當於類 [ \t\n\r\f\v]。

\S

  • Matches any non-whitespace character; this is equivalent to the class [^ \t\n\r\f\v].
    匹配任何非空白字元;它相當於類 [^ \t\n\r\f\v]。

\w

  • Matches any alphanumeric character; this is equivalent to the class [a-zA-Z0-9_].
    匹配任何字母數字字元;它相當於類 [a-zA-Z0-9_]。

\W

  • Matches any non-alphanumeric character; this is equivalent to the class [^a-zA-Z0-9_].
    匹配任何非字母數字字元;它相當於類 [^a-zA-Z0-9_]。

These sequences can be included inside a character class. For example, [\s,.] is a character class that will match any whitespace character, or "," or ".".
這樣特殊字元都可以包含在一個字元類中。如,[\s,.]字元類將匹配任何空白字元或","或"."。

The final metacharacter in this section is .. It matches anything except a newline character, and there's an alternate mode (re.DOTALL) where it will match even a newline. "." is often used where you want to match any character.
本節最後一個元字元是 . 。它匹配除了換行字元外的任何字元,在 alternate 模式(re.DOTALL)下它甚至可以匹配換行。"." 通常被用於你想匹配“任何字元”的地方。

2. Repeating Things(重複)

Being able to match varying sets of characters is the first thing regular expressions can do that isn't already possible with the methods available on strings. However, if that was the only additional capability of regexes, they wouldn't be much of an advance. Another capability is that you can specify that portions of the RE must be repeated a certain number of times.
正則表示式第一件能做的事是能夠匹配不定長的字符集,而這是其它能作用在字串上的方法所不能做到的。 不過,如果那是正則表示式唯一的附加功能的話,那麼它們也就不那麼優秀了。它們的另一個功能就是你可以指定正則表示式的一部分的重複次數。

The first metacharacter for repeating things that we'll look at is *. * doesn't match the literal character "*"; instead, it specifies that the previous character can be matched zero or more times, instead of exactly once.
我們討論的第一個重複功能的元字元是 *。* 並不匹配字母字元 "*";相反,它指定前一個字元可以被匹配零次或更多次,而不是隻有一次。

For example, ca*t will match "ct" (0 "a"characters), "cat" (1 "a"), "caaat" (3 "a"characters), and so forth. The RE engine has various internal limitations stemming from the size of C's int type, that will prevent it from matching over 2 billion "a" characters; you probably don't have enough memory to construct a string that large, so you shouldn't run into that limit.
舉個例子,ca*t 將匹配 "ct" (0 個 "a" 字元), "cat" (1 個 "a"), "caaat" (3 個 "a" 字元)等等。RE 引擎有各種來自 C 的整數型別大小的內部限制,以防止它匹配超過2億個 "a" 字元;你也許沒有足夠的記憶體去建造那麼大的字串,所以將不會累計到那個限制。

Repetitions such as * are greedy; when repeating a RE, the matching engine will try to repeat it as many times as possible. If later portions of the pattern don't match, the matching engine will then back up and try again with few repetitions.
象 * 這樣地重複是“貪婪的”;當重複一個 RE 時,匹配引擎會試著重複儘可能多的次數。如果模式的後面部分沒有被匹配,匹配引擎將退回並再次嘗試更小的重複。

A step-by-step example will make this more obvious. Let's consider the expression a[bcd]*b. This matches the letter "a", zero or more letters from the class [bcd], and finally ends with a "b". Now imagine matching this RE against the string "abcbd".
一步步的示例可以使它更加清晰。讓我們考慮表示式 a[bcd]*b。它匹配字母 "a",零個或更多個來自類 [bcd]中的字母,最後以 "b" 結尾。現在想一想該 RE 對字串 "abcbd" 的匹配。

Step

Matched

Explanation

1

a

The a in the RE matches.
a 匹配模式

2

abcbd

The engine matches [bcd]*, going as far as it can, which is to the end of the string.
引擎匹配 [bcd]*,並盡其所能匹配到字串的結尾

3

Failure

The engine tries to match b, but the current position is at the end of the string, so it fails.
引擎嘗試匹配 b,但當前位置已經是字元的最後了,所以失敗

4

abcb

Back up, so that [bcd]* matches one less character.
退回,[bcd]*嘗試少匹配一個字元。

5

Failure

Try b again, but the current position is at the last character, which is a "d".
再次嘗次b,但在當前最後一位字元是"d"。

6

abc

Back up again, so that [bcd]* is only matching "bc".
再次退回,[bcd]*只匹配 "bc"。

7

abcb

Try b again. This time but the character at the current position is "b", so it succeeds.
再次嘗試 b ,這次當前位上的字元正好是 "b"

The end of the RE has now been reached, and it has matched "abcb". This demonstrates how the matching engine goes as far as it can at first, and if no match is found it will then progressively back up and retry the rest of the RE again and again. It will back up until it has tried zero matches for [bcd]*, and if that subsequently fails, the engine will conclude that the string doesn't match the RE at all.
RE 的結尾部分現在可以到達了,它匹配 "abcb"。這證明了匹配引擎一開始會盡其所能進行匹配,如果沒有匹配然後就逐步退回並反覆嘗試 RE 剩下來的部分。直到它退回嘗試匹配 [bcd] 到零次為止,如果隨後還是失敗,那麼引擎就會認為該字串根本無法匹配 RE 。

Another repeating metacharacter is +, which matches one or more times. Pay careful attention to the difference between * and +; * matches zero or more times, so whatever's being repeated may not be present at all, while + requires at least one occurrence. To use a similar example, ca+t will match "cat" (1 "a"), "caaat" (3 "a"'s), but won't match "ct".
另一個重複元字元是 +,表示匹配一或更多次。請注意 * 和 + 之間的不同;* 匹配零或更多次,所以根本就可以不出現,而 + 則要求至少出現一次。用同一個例子,ca+t 就可以匹配 "cat" (1 個 "a"), "caaat" (3 個 "a"), 但不能匹配 "ct"。

There are two more repeating qualifiers. The question mark character, ?, matches either once or zero times; you can think of it as marking something as being optional. For example, home-?brew matches either "homebrew" or "home-brew".
還有更多的限定符。問號 ? 匹配一次或零次;你可以認為它用於標識某事物是可選的。例如:home-?brew 匹配 "homebrew" 或 "home-brew"。

The most complicated repeated qualifier is {m,n}, where m and n are decimal integers. This qualifier means there must be at least m repetitions, and at most n. For example, a/{1,3}b will match "a/b", "a//b", and "a///b". It won't match "ab", which has no slashes, or "a////b", which has four.
最複雜的重複限定符是 {m,n},其中 m 和 n 是十進位制整數。該限定符的意思是至少有 m 個重複,至多到 n 個重複。舉個例子,a/{1,3}b 將匹配 "a/b","a//b" 和 "a///b"。它不能匹配 "ab" 因為沒有斜槓,也不能匹配 "a////b" ,因為有四個。

You can omit either m or n; in that case, a reasonable value is assumed for the missing value. Omitting m is interpreted as a lower limit of 0, while omitting n results in an upper bound of infinity -- actually, the 2 billion limit mentioned earlier, but that might as well be infinity.
你可以忽略 m 或 n;因為會為缺失的值假設一個合理的值。忽略 m 會認為下邊界是 0,而忽略 n 的結果將是上邊界為無窮大 -- 實際上是先前我們提到的 2 兆,但這也許同無窮大一樣。

Readers of a reductionist bent may notice that the three other qualifiers can all be expressed using this notation. {0,} is the same as *, {1,} is equivalent to +, and {0,1} is the same as ?. It's better to use *, +, or ? when you can, simply because they're shorter and easier to read.
細心的讀者也許注意到其他三個限定符都可以用這樣方式來表示。 {0,} 等同於 *,{1,} 等同於 +,而{0,1}則與 ? 相同。如果可以的話,最好使用 *,+,或?。很簡單因為它們更短也再容易懂。

Using Regular Expressions(使用正則表示式)

Now that we've looked at some simple regular expressions, how do we actually use them in Python? The re module provides an interface to the regular expression engine, allowing you to compile REs into objects and then perform matches with them.
現在我們已經看了一些簡單的正則表示式,那麼我們實際在 Python 中是如何使用它們的呢? re 模組提供了一個正則表示式引擎的介面,可以讓你將 REs 編譯成物件並用它們來進行匹配。

1. Compiling Regular Expressions(編譯正則表示式)

Regular expressions are compiled into RegexObject instances, which have methods for various operations such as searching for pattern matches or performing string substitutions.
正則表示式被編譯成 RegexObject 例項,可以為不同的操作提供方法,如模式匹配搜尋或字串替換。

切換行號顯示 切換行號顯示 切換行號顯示
   1 >>> import re
   2 >>> p = re.compile('ab*')
   3 >>> print p
   4 <re.RegexObject instance at 80b4150>

re.compile() also accepts an optional flags argument, used to enable various special features and syntax variations. We'll go over the available settings later, but for now a single example will do:
re.compile() 也接受可選的標誌引數,常用來實現不同的特殊功能和語法變更。我們稍後將檢視所有可用的設定,但現在只舉一個例子:

切換行號顯示 切換行號顯示 切換行號顯示
   1 >>> p = re.compile('ab*', re.IGNORECASE)

The RE is passed to re.compile() as a string. REs are handled as strings because regular expressions aren't part of the core Python language, and no special syntax was created for expressing them. (There are applications that don't need REs at all, so there's no need to bloat the language specification by including them.) Instead, the re module is simply a C extension module included with Python, just like the socket or zlib module.
RE 被做為一個字串傳送給 re.compile()。REs 被處理成字串是因為正則表示式不是 Python 語言的核心部分,也沒有為它建立特定的語法。(應用程式根本就不需要 REs,因此沒必要包含它們去使語言說明變得臃腫不堪。)而 re 模組則只是以一個 C 擴充套件模組的形式來被 Python 包含,就象 socket 或 zlib 模組一樣。

Putting REs in strings keeps the Python language simpler, but has one disadvantage which is the topic of the next section.
將 REs 作為字串以保證 Python 語言的簡潔,但這樣帶來的一個麻煩就是象下節標題所講的。

2. The Backslash Plague(反斜槓的麻煩)

As stated earlier, regular expressions use the backslash character ("\") to indicate special forms or to allow special characters to be used without invoking their special meaning. This conflicts with Python's usage of the same character for the same purpose in string literals.
在早期規定中,正則表示式用反斜槓字元 ("\") 來表示特殊格式或允許使用特殊字元而不呼叫它的特殊用法。這就與 Python 在字串中的那些起相同作用的相同字元產生了衝突。

Let's say you want to write a RE that matches the string "\section", which might be found in a LATEX file. To figure out what to write in the program code, start with the desired string to be matched. Next, you must escape any backslashes and other metacharacters by preceding them with a backslash, resulting in the string "\\section". The resulting string that must be passed to re.compile() must be \\section. However, to express this as a Python string literal, both backslashes must be escaped again.
讓我們舉例說明,你想寫一個 RE 以匹配字串 "\section",可能是在一個 LATEX 檔案查詢。為了要在程式程式碼中判斷,首先要寫出想要匹配的字串。接下來你需要在所有反斜槓和元字元前加反斜槓來取消其特殊意義。

Characters(字元)

Stage(階段)

\section

Text string to be matched(要匹配的字串)

\\section

Escaped backslash for re.compile(為 re.compile 取消反斜槓的特殊意義)

"\\\\section"

Escaped backslashes for a string literal(為字串取消反斜槓)

In short, to match a literal backslash, one has to write '\\\\' as the RE string, because the regular expression must be "\\", and each backslash must be expressed as "\\" inside a regular Python string literal. In REs that feature backslashes repeatedly, this leads to lots of repeated backslashes and makes the resulting strings difficult to understand.
簡單地說,為了匹配一個反斜槓,不得不在 RE 字串中寫 '\\\\',因為正則表示式中必須是 "\\",而每個反斜槓按 Python 字串字母表示的常規必須表示成 "\\"。在 REs 中反斜槓的這個重複特性會導致大量重複的反斜槓,而且所生成的字串也很難懂。

The solution is to use Python's raw string notation for regular expressions; backslashes are not handled in any special way in a string literal prefixed with "r", so r"\n" is a two-character string containing "\" and "n", while "\n" is a one-character string containing a newline. Frequently regular expressions will be expressed in Python code using this raw string notation.
解決的辦法就是為正則表示式使用 Python 的 raw 字串表示;在字串前加個 "r" 反斜槓就不會被任何特殊方式處理,所以 r"\n" 就是包含"\" 和 "n" 的兩個字元,而 "\n" 則是一個字元,表示一個換行。正則表示式通常在 Python 程式碼中都是用這種 raw 字串表示。

Regular String(常規字串)

Raw string(Raw 字串)

"ab*"

r"ab*"

"\\\\section"

r"\\section"

"\\w+\\s+\\1"

r"\w+\s+\1"

3. Performing Matches(執行匹配)

Once you have an object representing a compiled regular expression, what do you do with it? RegexObject instances have several methods and attributes. Only the most significant ones will be covered here; consult the Library Reference for a complete listing.
一旦你有了已經編譯了的正則表示式的物件,你要用它做什麼呢?RegexObject 例項有一些方法和屬性。這裡只顯示了最重要的幾個,如果要看完整的列表請查閱 Library Refference。

Method/Attribute(方法/屬性)

Purpose(作用)

match()

Determine if the RE matches at the beginning of the string.
決定 RE 是否在字串剛開始的位置匹配

search()

Scan through a string, looking for any location where this RE matches.
掃描字串,找到這個 RE 匹配的位置

findall()

Find all substrings where the RE matches, and returns them as a list.
找到 RE 匹配的所有子串,並把它們作為一個列表返回

finditer()

Find all substrings where the RE matches, and returns them as an iterator.
找到 RE 匹配的所有子串,並把它們作為一個迭代器返回

match() and search() return None if no match can be found. If they're successful, a MatchObject instance is returned, containing information about the match: where it starts and ends, the substring it matched, and more.
如果沒有匹配到的話,match() 和 search() 將返回 None。如果成功的話,就會返回一個 MatchObject 例項,其中有這次匹配的資訊:它是從哪裡開始和結束,它所匹配的子串等等。

You can learn about this by interactively experimenting with the re module. If you have Tkinter available, you may also want to look at Tools/scripts/redemo.py, a demonstration program included with the Python distribution. It allows you to enter REs and strings, and displays whether the RE matches or fails. redemo.py can be quite useful when trying to debug a complicated RE. Phil Schwartz's Kodos is also an interactive tool for developing and testing RE patterns. This HOWTO will use the standard Python interpreter for its examples.
你可以用採用人機對話並用 re 模組實驗的方式來學習它。如果你有 Tkinter 的話,你也許可以考慮參考一下 Tools/scripts/redemo.py,一個包含在 Python 發行版裡的示範程式。

First, run the Python interpreter, import the re module, and compile a RE:
首先,執行 Python 直譯器,匯入 re 模組並編譯一個 RE:

切換行號顯示 切換行號顯示 切換行號顯示
   1 Python 2.2.2 (#1, Feb 10 2003, 12:57:01)
   2 >>> import re
   3 >>> p = re.compile('[a-z]+')
   4 >>> p
   5 <_sre.SRE_Pattern object at 80c3c28>
ERROR: EOF in multi-line statement

Now, you can try matching various strings against the RE [a-z]+. An empty string shouldn't match at all, since + means 'one or more repetitions'. match() should return None in this case, which will cause the interpreter to print no output. You can explicitly print the result of match() to make this clear.
現在,你可以試著用 RE 的 [a-z]+ 去匹配不同的字串。一個空字串將根本不能匹配,因為 + 的意思是 “一個或更多的重複次數”。 在這種情況下 match() 將返回 None,因為它使直譯器沒有輸出。你可以明確地打印出 match() 的結果來弄清這一點。

切換行號顯示 切換行號顯示 切換行號顯示
   1 >>> p.match("")
   2 >>> print p.match("")
   3 None

Now, let's try it on a string that it should match, such as "tempo". In this case, match() will return a MatchObject, so you should store the result in a variable for later use.
現在,讓我們試著用它來匹配一個字串,如 "tempo"。這時,match() 將返回一個 MatchObject。因此你可以將結果儲存在變數裡以便後面使用。

切換行號顯示 切換行號顯示 切換行號顯示
   1 >>> m = p.match( 'tempo')
   2 >>> print m
   3 <_sre.SRE_Match object at 80c4f68>

Now you can query the MatchObject for information about the matching string. MatchObject instances also have several methods and attributes; the most important ones are:
現在你可以查詢 MatchObject 關於匹配字串的相關資訊了。MatchObject 例項也有幾個方法和屬性;最重要的那些如下所示:

Method/Attribute(方法/屬性)

Purpose(作用)

group()

Return the string matched by the RE
返回被 RE 匹配的字串

start()

Return the starting position of the match
返回匹配開始的位置

end()

Return the ending position of the match
返回匹配結束的位置

span()

Return a tuple containing the (start, end) positions of the match
返回一個元組包含匹配 (開始,結束) 的位置

Trying these methods will soon clarify their meaning:
試試這些方法不久就會清楚它們的作用了:

切換行號顯示 切換行號顯示 切換行號顯示
   1 >>> m.group()
   2 'tempo'
   3 >>> m.start(), m.end()
   4 (0, 5)
   5 >>> m.span()
   6 (0, 5)

group() returns the substring that was matched by the RE. start() and end() return the starting and ending index of the match. span() returns both start and end indexes in a single tuple. Since the match method only checks if the RE matches at the start of a string, start() will always be zero. However, the search method of RegexObject instances scans through the string, so the match may not start at zero in that case.
group() 返回 RE 匹配的子串。start() 和 end() 返回匹配開始和結束時的索引。span() 則用單個元組把開始和結束時的索引一起返回。因為匹配方法檢查到如果 RE 在字串開始處開始匹配,那麼 start() 將總是為零。然而, RegexObject 例項的 search 方法掃描下面的字串的話,在這種情況下,匹配開始的位置就也許不是零了。

切換行號顯示 切換行號顯示 切換行號顯示
   1 >>> print p.match('::: message')
   2 None
   3 >>> m = p.search('::: message') ; print m
   4 <re.MatchObject instance at 80c9650>
   5 >>> m.group()
   6 'message'
   7 >>> m.span()
   8 (4, 11)

In actual programs, the most common style is to store the MatchObject in a variable, and then check if it was None. This usually looks like:
在實際程式中,最常見的作法是將 MatchObject 儲存在一個變數裡,然後檢查它是否為 None,通常如下所示:

切換行號顯示 切換行號顯示 切換行號顯示
   1 p = re.compile( ... )
   2 m = p.match( 'string goes here' )
   3 if m:
   4     print 'Match found: ', m.group()
   5 else:
   6     print 'No match'

Two RegexObject methods return all of the matches for a pattern. findall() returns a list of matching strings:
兩個 RegexObject 方法返回所有匹配模式的子串。findall()返回一個匹配字串列表:

切換行號顯示 切換行號顯示 切換行號顯示
   1 >>> p = re.compile('\d+')
   2 >>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
   3 ['12', '11', '10']

findall() has to create the entire list before it can be returned as the result. In Python 2.2, the finditer() method is also available, returning a sequence of MatchObject instances as an iterator.
findall() 在它返回結果時不得不建立一個列表。在 Python 2.2中,也可以用 finditer() 方法。

切換行號顯示 切換行號顯示 切換行號顯示
   1 >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
   2 >>> iterator
   3 <callable-iterator object at 0x401833ac>
   4 >>> for match in iterator:
   5 ...     print match.span()
   6 ...
   7 (0, 2)
   8 (22, 24)
   9 (29, 31)

4. Module-Level Functions(模組級函式)

You don't have to produce a RegexObject and call its methods; the re module also provides top-level functions called match(), search(), sub(), and so forth. These functions take the same arguments as the corresponding RegexObject method, with the RE string added as the first argument, and still return either None or a MatchObject instance.
你不一定要產生一個 RegexObject 物件然後再呼叫它的方法;re 模組也提供了頂級函式呼叫如 match()、search()、sub() 等等。這些函式使用 RE 字串作為第一個引數,而後面的引數則與相應 RegexObject 的方法引數相同,返回則要麼是 None 要麼就是一個 MatchObject 的例項。

切換行號顯示 切換行號顯示 切換行號顯示
   1 >>> print re.match(r'From\s+', 'Fromage amk')
   2 None
   3 >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')
   4 <re.MatchObject instance at 80c5978>

Under the hood, these functions simply produce a RegexObject for you and call the appropriate method on it. They also store the compiled object in a cache, so future calls using the same RE are faster.
Under the hood, 這些函式簡單地產生一個 RegexOject 並在其上呼叫相應的方法。它們也在快取裡儲存編譯後的物件,因此在將來呼叫用到相同 RE 時就會更快。

Should you use these module-level functions, or should you get the RegexObject and call its methods yourself? That choice depends on how frequently the RE will be used, and on your personal coding style. If a RE is being used at only one point in the code, then the module functions are probably more convenient. If a program contains a lot of regular expressions, or re-uses the same ones in several locations, then it might be worthwhile to collect all the definitions in one place, in a section of code that compiles all the REs ahead of time. To take an example from the standard library, here's an extract from xmllib.py: 你將使用這些模組級函式,還是先得到一個 RegexObject 再呼叫它的方法呢?如何選擇依賴於怎樣用 RE 更有效率以及你個人編碼風格。如果一個 RE 在程式碼中只做用一次的話,那麼模組級函式也許更方便。如果程式包含很多的正則表示式,或在多處複用同一個的話,那麼將全部定義放在一起,在一段程式碼中提前編譯所有的 REs 更有用。從標準庫中看一個例子,這是從 xmllib.py 檔案中提取出來的:

切換行號顯示 切換行號顯示 切換行號顯示
   1 ref = re.compile( ... )
   2 entityref = re.compile( ... )
   3 charref = re.compile( ... )
   4 starttagopen = re.compile( ... )

I generally prefer to work with the compiled object, even for one-time uses, but few people will be as much of a purist about this as I am.
我通常更喜歡使用編譯物件,甚至它只用一次,but few people will be as much of a purist about this as I am。

5. Compilation Flags(編譯標誌)

Compilation flags let you modify some aspects of how regular expressions work. Flags are available in the re module under two names, a long name such as IGNORECASE, and a short, one-letter form such as I. (If you're familiar with Perl's pattern modifiers, the one-letter forms use the same letters; the short form of re.VERBOSE is re.X, for example.) Multiple flags can be specified by bitwise OR-ing them; re.I | re.M sets both the I and M flags, for example.
編譯標誌讓你可以修改正則表示式的一些執行方式。在 re 模組中標誌可以使用兩個名字,一個是全名如 IGNORECASE,一個是縮寫,一字母形式如 I。(如果你熟悉 Perl 的模式修改,一字母形式使用同樣的字母;例如 re.VERBOSE的縮寫形式是 re.X。)多個標誌可以通過按位 OR-ing 它們來指定。如 re.I | re.M 被設定成 I 和 M 標誌:

Here's a table of the available flags, followed by a more detailed explanation of each one.
這有個可用標誌表,對每個標誌後面都有詳細的說明。

Flag(標誌)

Meaning(含義)

DOTALL, S

Make . match any character, including newlines
使 . 匹配包括換行在內的所有字元

IGNORECASE, I

Do case-insensitive matches
使匹配對大小寫不敏感

LOCALE, L

Do a locale-aware match
做本地化識別(locale-aware)匹配

MULTILINE, M

Multi-line matching, affecting and $[[BR]]多行匹配,影響 和 $

VERBOSE, X

Enable verbose REs, which can be organized more cleanly and understandably.
能夠使用 REs 的 verbose 狀態,使之被組織得更清晰易懂

I
IGNORECASE

  • Perform case-insensitive matching; character class and literal strings will match