Python中的re模塊

<h3>Python中的re模塊</h3>

Python中提供perl風格的正則表達式模式,re模塊使Python擁有全部的正則表達式功能富寿。

compile函數(shù)根據(jù)一個模式字符串和可選標志參數(shù)生成一個正則表達式對象,這個對象擁有一系列方法用于正則表達式匹配和替換轩缤。

re模塊提供了與這些方法功能完全一致的函數(shù)酒繁,這些函數(shù)使用一個模式字符串作為他們的第一個參數(shù)。

本文介紹re模塊的主要函數(shù)和用法捶索。


re.py中關于一些特殊字符的定義

r"""
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.
    "$"      匹配字符串結(jié)尾或字符串結(jié)尾換行符之前
    "*"      Matches 0 or more (greedy) repetitions of the preceding RE.Greedy means that it will match as many repetitions as possible.
    "*"      匹配0或者 更多(貪婪)。貪婪意味著它會盡可能的匹配更多
             
    "+"      Matches 1 or more (greedy) repetitions of the preceding RE.
    "+"      匹配1或者更多灰瞻。
    "?"      Matches 0 or 1 (greedy) of the preceding RE.
    "?"      盡可能的匹配1或者0
    *?,+?,?? 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.
    (?aiLmsux) Set the A, 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.""

r"""The special sequences consist of "\\" and a character from the list below.  If the ordinary character is not on the list, then the resulting 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] in bytes patterns or string patterns with the ASCII flag. In string patterns without the ASCII flag, it will match the whole range of Unicode digits.
    \d      匹配任何十進制整數(shù);相當于字節(jié)模式的集合[0-9]或者有ASCII標志的字符串模式腥例。在沒有ASCII標志的字符串模式辅甥,它將匹配所有的Unicode整數(shù)
    \D       Matches any non-digit character; equivalent to [^\d].
    \D       匹配任何非數(shù)字字符;相當于[^\d]
    \s       Matches any whitespace character; equivalent to [ \t\n\r\f\v] in bytes patterns or string patterns with the ASCII flag.In string patterns without the ASCII flag, it will match the whole range of Unicode whitespace characters.
    \s       匹配任何空格字符;相當于具有ASCII標志的字節(jié)模式或字符串模式中的[\ t \ n \ r \ f \ v]燎竖。在沒有ASCII標志的字符串模式中璃弄,它將匹配Unicode空格字符的整個范圍。
    \S       Matches any non-whitespace character; equivalent to [^\s].
    \S       匹配任何非空字符构回;相當于[^\s]夏块。
    \w       Matches any alphanumeric character; equivalent to [a-zA-Z0-9_] in bytes patterns or string patterns with the ASCII flag.  In string patterns without the ASCII flag, it will match the range of Unicode alphanumeric characters (letters plus digits plus underscore). With LOCALE, it will match the set [0-9_] plus characters defined as letters for the current locale.
    \w       配任何字母數(shù)字字符;相當于[a-zA-Z0-9_]字節(jié)模式或帶ASCII標志的字符串模式。在沒有ASCII標志的字符串模式中纤掸,它將匹配Unicode字母數(shù)字字符(字母加數(shù)字和下劃線)的范圍脐供。使用LOCALE,它將匹配定義為當前語言環(huán)境的字母的集[0-9_]加字符借跪。
    \W       Matches the complement of \w.
    \W       匹配\w的補碼 
    \\       Matches a literal backslash.
    \\       匹配反斜杠

python的re模塊包含以下函數(shù):

r"""
    match     Match a regular expression pattern to the beginning of a string.
    match     從字符串開頭匹配正則表達式政己。
    fullmatch Match a regular expression pattern to all of a string.
    fullmatch  從整個字符串匹配正則表達式
    search    Search a string for the presence of a pattern.
    search    
    sub       Substitute occurrences of a pattern found in a string.
    sub       替換在字符串
    subn      Same as sub, but also return the number of substitutions made.
    subn      和sub一樣,但是返回所做替換的次數(shù)
    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."""

該模塊中的一些功能將標志作為可選參數(shù):

r"""
    A  ASCII       For string patterns, make \w, \W, \b, \B, \d, \D match the corresponding ASCII character categories  (rather than the whole Unicode categories, which is the default). For bytes patterns, this flag is the only available behaviour and needn't be specified.
    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     For compatibility only. Ignored for string patterns (it is the default), and forbidden for bytes patterns."""

re模塊中同樣定義了一個異常"錯誤".掏愁。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末歇由,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子果港,更是在濱河造成了極大的恐慌沦泌,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件辛掠,死亡現(xiàn)場離奇詭異谢谦,居然都是意外死亡,警方通過查閱死者的電腦和手機萝衩,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進店門回挽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人欠气,你說我怎么就攤上這事厅各。” “怎么了预柒?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵队塘,是天一觀的道長。 經(jīng)常有香客問我宜鸯,道長憔古,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任淋袖,我火速辦了婚禮鸿市,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己焰情,他們只是感情好陌凳,可當我...
    茶點故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著内舟,像睡著了一般合敦。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上验游,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天充岛,我揣著相機與錄音,去河邊找鬼耕蝉。 笑死崔梗,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的垒在。 我是一名探鬼主播蒜魄,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼爪膊!你這毒婦竟也來了权悟?” 一聲冷哼從身側(cè)響起砸王,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤推盛,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后谦铃,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體耘成,經(jīng)...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年驹闰,在試婚紗的時候發(fā)現(xiàn)自己被綠了瘪菌。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡嘹朗,死狀恐怖师妙,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情屹培,我是刑警寧澤默穴,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站褪秀,受9級特大地震影響蓄诽,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜媒吗,卻給世界環(huán)境...
    茶點故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一仑氛、第九天 我趴在偏房一處隱蔽的房頂上張望唾戚。 院中可真熱鬧,春花似錦游盲、人聲如沸仪芒。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽米酬。三九已至,卻和暖如春趋箩,著一層夾襖步出監(jiān)牢的瞬間赃额,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工叫确, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留跳芳,地道東北人。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓竹勉,卻偏偏與公主長得像飞盆,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子次乓,可洞房花燭夜當晚...
    茶點故事閱讀 45,037評論 2 355

推薦閱讀更多精彩內(nèi)容