Python 正則表達式 Howto(1)

很久沒有寫博客了, 都有點忘記如何操作了。 

最近閒暇時學習了一下python, 覺得中文的資料實在是太.... 所以看了一些官網上的HOWTO, 覺得不錯, 翻譯一下給大家共享。 希望能對喜歡python 的有所幫助。 爲了督促自己能完成這個系列的翻譯, 所以在這裏標記一下。 爲了不誤導讀者, 我把原文也貼上了~


原文地址:http://docs.python.org/dev/howto/regex.html


Introduction

Regular expressions (called REs, or regexes, or regex patterns) 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.

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.

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.

開篇

正則表達式(RE 模塊)是python中內嵌的一個微型的, 定製化程度極高的編程語言, 在python中通過re模塊來實現的。利用正則表達式, 你可以爲各種你想匹配的文本設計不同的規則, 你可以用來匹配英文句子,email地址, tex 命令, 甚至於中文, 反正你喜歡的東西就可以匹配,找出你需要的東西。 “這個字符串符合這個規則麼?” 或者是“這個字符串中有我想要的匹配麼?”這些問題你都可以在正則匹配中找到答案。 此外, 正則表達式還能修改字符串, 還能做字符串切割。 總而言之,正則表達式是一個相當相當強大的工具:) 

在python中,正則表達式的引擎是使用C寫的, 所以你不用懷疑其效率。 正則表達式會被編譯成字節碼,這些字節碼使用C編譯的引擎執行。 在一些高級的應用中,我們需要注意RE的引擎室如何實現的,或者是我們需要理解python的匹配引擎,這樣我們才能寫出運行快的正則表達式。 這個文檔只是一個howto文檔, 至於優化方面的內容, 除了學好python的正則表達式之外,你還得花點時間學學正則表達式的原理, 推薦《精通正則表達式》我在看這本書, 不過太忙了, 只能囫圇吞棗。 

正則表達式是一門及其精簡,定製化程度極高的語言,這句話另外一層含義就是不是所有的工作都可以使用正則表達式完成。(以前在I司工作的使用,有個項目使用正則表達式抓取網頁中的注入代碼, 就遇到一些不能處理的情況。 )另外有些工作可以使用正則表達式完成, 但是耗費的精力遠遠超過使用普通python語言,這種情況下就拋棄RE吧, 直接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.


從簡單的模式開始

讓我們先從匹配字符開始吧。字符匹配是最簡單的匹配方式, 這個毋庸置疑, 但是學好字符匹配也得記住一些東西。 再次重申, 本文只是一個HOWTO, 至於一些正則匹配背後的浩大的計算機科學原理,翻一翻大學裏學習的編譯原理吧(當年覺得這門課奇難,花了很多的新思, 最後成績都不理想,偶有一同學, 奇猛, 看了幾天書, 就可以融會貫通, 佩服之!)


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.)

There are exceptions to this rule; some characters are special metacharacters, 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 or changing their meaning. Much of this document is devoted to discussing various metacharacters and what they do.

字符匹配

對於大多數字符而言, 匹配字符就是他們自己。比如說, 我打算精確匹配’test‘, 我就是簡單的使用模式’test‘就可以了。 (學英語的人可要注意了, 英語是有大寫小寫的, re模塊已經考慮到這點了, 誰讓是老外寫的呢? 你可以使能大小寫敏感模式, 這樣test就可以匹配test 或者TEST了, 後面詳論)。


我最恨意外了, 但是凡事總有意外。一些字符回座位特殊匹配字符。 這些字符不能匹配他們自己, 而是具有特異功能。這些字符通過重複, 轉義等特殊功能影響着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 ab, 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].

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.

You can match the characters not listed within the class by complementing the set. This is indicated by including a '^' as the first character of the class;'^' outside a character class will simply match the '^' character. For example, [^5] will match any character except '5'.

我們首先來看[], 這個中括號可不簡單, 在正則匹配中,他們用來標示一個用來匹配的字符集。 我們可以在[]中單列, 也可以給出一個範圍, 如果是給你範圍的話需要用'-'隔開。 來個例子吧, 更容易理解。比如, 我們想匹配a,b,c,或者是d, 我們可以使用[abcd]也可以簡單的寫成[a-d]。 給個更加有用的例子,我們想匹配所有的小寫字符, [a-z] 就可以了, 不用[abcdefgh。。。]累死了。 這規則表達式的作者替你考慮到這些了 :)

特殊字符在[]中就變的不特殊了, 他們就會蛻變成平頭百姓, 不再具有特殊功能。來個例子吧。[akm$]會匹配'a''k''m', 或者'$'中的任意字符。'$' 本來是特殊字符, 但是在[]中就無能爲力了。 

另外一種操作方式是求補集, 這種方式可以讓你匹配不再這個集合中的字符。 求補集(取反)通過在[]的開始出使用字符‘^’實現。在[]使用'^', 只會簡單的匹配'^'字符, 並不具有取反的功能。 權利是有範圍的:) 例子[^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 \\.

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 a subset of those available. The equivalent classes are for bytes patterns. For a complete list of sequences and expanded class definitions for Unicode string patterns, see the last part of Regular Expression Syntax.

最麻煩的同時也是最重要的可能就是反斜槓了(從大學中學習C就開始學習這個特殊字符, 功能太強大)。 在python的字符串中, 反斜槓可以作用在很多的字符上完成特殊的功能。 另外他也可以讓特殊字符迴歸其本來面目。 來個例子, []是特殊字符, 你想匹配'[', 你就得用'\['(當然你也可以使用[[])。還有一個例子就是\, 我們要匹配這個字符, 我們就得使用\\。 我們想匹配\\ 我們就得用\\\\。 太麻煩了~

一些預先定義的以\開始的序列非常有用, 這些序列往往代表一類字符。 比如數字, 字母,非空字串等等。下面列出了常用一些序列,記住他們,非常有用。至於一個非常全的,包含擴展類定義以及unicode的規則,請參見《正則表達式語法》


\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].
 匹配空白字符,比如空格,tab,回車等等。等價於[ \t\n\r\f\v] (\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”.

最後一個特殊字符時., 這個字符能匹配任意字符, 但是不能誇行,換句話說這個字符不能匹配\n. (這一點得注意)。 如果你想匹配所有的字符, 不能使用. 。有兩種方法解決這個問題, 使用[\s\S]或者使用re.DOTALL這種模式。 




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章