正則表達式語法表如下:
語法 | 意義 | 說明 |
"." | 任意字符 | |
"^" | 字符串開始 | '^hello'匹配'helloworld'而不匹配'aaaahellobbb' |
"$" | 字符串結尾 | 與上同理 |
"*" | 0 個或多個字符(貪婪匹配) | <*>匹配<title>chinaunix</title> |
"+" | 1 個或多個字符(貪婪匹配) | 與上同理 |
"?" | 0 個或多個字符(貪婪匹配) | 與上同理 |
*?,+?,?? | 以上三個取第一個匹配結果(非貪婪匹配) | <*>匹配<title> |
{m,n} | 對於前一個字符重復m到n次,{m}亦可 | a{6}匹配6個a、a{2,4}匹配2到4個a |
{m,n}? | 對於前一個字符重復m到n次,並取盡可能少 | ‘aaaaaa’中a{2,4}只會匹配2個 |
"\\" | 特殊字符轉義或者特殊序列 | |
[] | 表示一個字符集 | [0-9]、[a-z]、[A-Z]、[^0] |
"|" | 或 | A|B,或運算 |
(...) | 匹配括號中任意表達式 | |
(?#...) | 注釋,可忽略 | |
(?=...) | Matches if ... matches next, but doesn't consume the string. | '(?=test)' 在hellotest中匹配hello |
(?!...) | Matches if ... doesn't match next. | '(?!=test)' 若hello后面不為test,匹配hello |
(?<=...) | Matches if preceded by ... (must be fixed length). | '(?<=hello)test' 在hellotest中匹配test |
(?<!...) | Matches if not preceded by ... (must be fixed length). | '(?<!hello)test' 在hellotest中不匹配test |
特殊序列符號 | 意義 |
\A | 只在字符串開始進行匹配 |
\Z | 只在字符串結尾進行匹配 |
\b | 匹配位於開始或結尾的空字符串 |
\B | 匹配不位於開始或結尾的空字符串 |
\d | 相當於[0-9] |
\D | 相當於[^0-9] |
\s | 匹配任意空白字符:[\t\n\r\r\v] |
\S | 匹配任意非空白字符:[^\t\n\r\r\v] |
\w | 匹配任意數字和字母:[a-zA-Z0-9] |
\W | 匹配任意非數字和字母:[^a-zA-Z0-9] |
re.match()
從字符串的起點開始做匹配
Python 2.7.6 (default, Nov 10 2013, 19:24:24) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import re
>>> re.match("a","abcdefg")
<_sre.SRE_Match object at 0x0000000002D74988> #表示匹配成功
>>>print re.match("a","cabacdefg")
None #表示怕匹配失敗 返回空
re.search()
字符串做任意匹配
>>> re.search("a","bcdefag")
<_sre.SRE_Match object at 0x0000000002D74988> #表示匹配成功
>>>print re.searc("k","cabcdefg")
None #表示怕匹配失敗 返回空
re.compile() #表示不是很明白 講正則表達式編譯成對象
>>> a1 = re.compile("a")
>>> print a1.search("bcdefag")
<_sre.SRE_Match object at 0x0000000002D749F0>
等價於 re.search("a","bcdefag")
正則表達式 可以多次重復使用 速度效率更高更快
re.split(pattern, string, maxsplit=0) #分隔字符串
>>> re.split('w', 'howareyou') #講howareyou 按照小寫w分隔 並返回列表
['ho', 'areyou']
re.findall(pattern,string,flags=0)
找到 RE 匹配的所有子串,並把它們作為一個列表返回。這個匹配是從左到右有序地返回。如果無匹配,返回空列表。
>>> re.findall(r"\d+","12a32bc43jf3") #\d 表示匹配數字 +表示匹配一個或者多個
['12', '32', '43', '3']