Python正則表達式集錦


if 你只有5min:

  讀Python的正則提取技巧

  return

else:

Python正則表達式指南

Python正則表達式的用法

Python正則表達式操作指南

regular_expressions_cheat_sheet


match和search的區別

        Python提供了兩種不同的原始操作:match和search。match是從字符串的起點開始做匹配,而search(perl默認)是從字符串做任意匹配。

        注意:當正則表達式是' ^ '開頭時,match與search是相同的。match只有當且僅當被匹配的字符串開頭就能匹配 或 從pos參數的位置開始就能匹配 時才會成功。如下:


貪婪模式?,+,*,{m[,n]}

>>> import re
>>> m = re.search("(book)+","mebookbookme")
>>> m.group()
'bookbook'
>>> m.groups()
('book',)
>>> re.findall("(book)+","mebookbookme")
['book']
 
        
>>> m = re.search("((?:book)+)","mebookbookme")
>>> m.group()
'bookbook'
>>> m.groups()
('bookbook',)
>>> re.findall("((?:book)+)","mebookbookme")
['bookbook']
 
        
>>> m = re.search("(book+)","mebookbookme")
>>> m.group()
'book'
>>> m.groups()
('book',)
>>> re.findall("(book+)","mebookbookme")
['book', 'book']

python非貪婪、多行匹配正則表達式例子


Python 正則提取並賦值的問題

Python對unicode文件的讀寫和使用正則表達式

python類庫31[正則表達式]


常用正則表達式

驗證數字的正則表達式集

匹配特定數字:
^[1-9]\d*$    //匹配正整數
^-[1-9]\d*$   //匹配負整數
^-?[1-9]\d*$   //匹配整數
^[1-9]\d*|0$  //匹配非負整數(正整數 + 0)
^-[1-9]\d*|0$   //匹配非正整數(負整數 + 0)
^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$   //匹配正浮點數
^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$  //匹配負浮點數
^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$  //匹配浮點數
^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$   //匹配非負浮點數(正浮點數 + 0)
^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$  //匹配非正浮點數(負浮點數 + 0)
評注:處理大量數據時有用,具體應用時注意修正

匹配特定字符串:
^[A-Za-z]+$  //匹配由26個英文字母組成的字符串
^[A-Z]+$  //匹配由26個英文字母的大寫組成的字符串
^[a-z]+$  //匹配由26個英文字母的小寫組成的字符串
^[A-Za-z0-9]+$  //匹配由數字和26個英文字母組成的字符串
^\w+$  //匹配由數字、26個英文字母或者下划線組成的字符串

匹配中文字符的正則表達式: [\u4e00-\u9fa5]
評注:匹配中文還真是個頭疼的事,有了這個表達式就好辦了

匹配雙字節字符(包括漢字在內):[^\x00-\xff]
評注:可以用來計算字符串的長度(一個雙字節字符長度計2,ASCII字符計1)

匹配空白行的正則表達式:\n\s*\r
評注:可以用來刪除空白行

匹配HTML標記的正則表達式:<(\S*?)[^>]*>.*?</\1>|<.*? />
評注:網上流傳的版本太糟糕,上面這個也僅僅能匹配部分,對於復雜的嵌套標記依舊無能為力

匹配首尾空白字符的正則表達式:^\s*|\s*$
評注:可以用來刪除行首行尾的空白字符(包括空格、制表符、換頁符等等),非常有用的表達式

匹配Email地址的正則表達式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
評注:表單驗證時很實用

匹配網址URL的正則表達式:[a-zA-z]+://[^\s]*
評注:網上流傳的版本功能很有限,上面這個基本可以滿足需求

匹配帳號是否合法(字母開頭,允許5-16字節,允許字母數字下划線):^[a-zA-Z][a-zA-Z0-9_]{4,15}$
評注:表單驗證時很實用

匹配國內電話號碼:\d{3}-\d{8}|\d{4}-\d{7}
評注:匹配形式如 0511-4405222 或 021-87888822

匹配騰訊QQ號:[1-9][0-9]{4,}
評注:騰訊QQ號從10000開始

匹配中國郵政編碼:[1-9]\d{5}(?!\d)
評注:中國郵政編碼為6位數字

匹配身份證:\d{15}|\d{18}
評注:中國的身份證為15位或18位

匹配ip地址:\d+\.\d+\.\d+\.\d+
評注:提取ip地址時有用

 

整數:^-?\d+$
非負浮點數(正浮點數 + 0):^\d+(\.\d+)?$
正浮點數   ^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$
非正浮點數(負浮點數 + 0) ^((-\d+(\.\d+)?)|(0+(\.0+)?))$
負浮點數  ^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$
浮點數  ^(-?\d+)(\.\d+)?$

 

驗證非零的正整數:^\+?[1-9][0-9]*$
驗證非零的負整數:^\-[1-9][0-9]*$
驗證非負整數(正整數 + 0)  ^\d+$
驗證非正整數(負整數 + 0)  ^((-\d+)|(0+))$

驗證數字:^[0-9]*$
驗證n位的數字:^\d{n}$
驗證至少n位數字:^\d{n,}$
驗證m-n位的數字:^\d{m,n}$
驗證零和非零開頭的數字:^(0|[1-9][0-9]*)$
驗證有兩位小數的正實數:^[0-9]+(.[0-9]{2})?$
驗證有1-3位小數的正實數:^[0-9]+(.[0-9]{1,3})?$


驗證用戶密碼:^[a-zA-Z]\w{5,17}$ 正確格式為:以字母開頭,長度在6-18之間,只能包含字符、數字和下划線。
驗證是否含有 ^%&',;=?$\" 等字符:[^%&',;=?$\x22]+
驗證漢字:^[\u4e00-\u9fa5],{0,}$
驗證Email地址:^\w+[-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$
驗證InternetURL:^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$ ;^[a-zA-z]+://(w+(-w+)*)(.(w+(-w+)*))*(?S*)?$
驗證電話號碼:^(\(\d{3,4}\)|\d{3,4}-)?\d{7,8}$:--正確格式為:XXXX-XXXXXXX,XXXX-XXXXXXXX,XXX-XXXXXXX,XXX-XXXXXXXX,XXXXXXX,XXXXXXXX。
驗證身份證號(15位或18位數字):^\d{15}|\d{}18$
驗證一年的12個月:^(0?[1-9]|1[0-2])$ 正確格式為:“01”-“09”和“1”“12”
驗證一個月的31天:^((0?[1-9])|((1|2)[0-9])|30|31)$    正確格式為:01、09和1、31。


DESCRIPTION
    This module provides regular expression matching operations similar to
    those found in Perl.  It supports both 8-bit and Unicode strings; both
    the pattern and the strings being processed can contain null bytes and
    characters outside the US ASCII range.
   
    Regular expressions can contain both special and ordinary characters.
    Most ordinary characters, like "A", "a", or "0", are the simplest
    regular expressions; they simply match themselves.  You can
    concatenate ordinary characters, so last matches the string 'last'.
   
    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 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].
        \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.
   
    This module also defines an exception 'error'.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM