一、Python中逸出字元
Regex使用反斜線" \ "來代表特殊形式或用作逸出字元,這裡跟Python的文法衝突,因此,Python用" \\\\ "表示Regex中的" \ ",因為Regex中如果要匹配" \ ",需要用\來轉義,變成" \\ ",而Python文法中又需要對字串中每一個\進行轉義,所以就變成了" \\\\ "。
上面的寫法是不是覺得很麻煩,為了使Regex具有更好的可讀性,Python特別設計了原始字串(raw string),需要提醒你的是,在寫檔案路徑的時候就不要使用raw string了,這裡存在陷阱。raw string就是用'r'作為字串的首碼,如 r"\n":表示兩個字元"\"和"n",而不是分行符號了。Python中寫Regex時推薦使用這種形式。
二、Regex元字元說明:
. 匹配除分行符號以外的任一字元
^ 匹配字串的開始
$ 匹配字串的結束
[] 用來匹配一個指定的字元類別
? 對於前一個字元字元重複0次到1次
* 對於前一個字元重複0次到無窮次
{} 對於前一個字元重複m次
{m,n} 對前一個字元重複為m到n次
\d 匹配數字,相當於[0-9]
\D 匹配任何非數字字元,相當於[^0-9]
\s 匹配任意的空白符,相當於[ fv]
\S 匹配任何非空白字元,相當於[^ fv]
\w 匹配任何字母數字字元,相當於[a-zA-Z0-9_]
\W 匹配任何非字母數字字元,相當於[^a-zA-Z0-9_]
\b 匹配單詞的開始或結束
三、匯入Regex模組
3.1、匯入Regex模組
>>> import re
3.2、查看Regex模組方法
>>> dir(re)['DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__version__', '_alphanum', '_cache', '_cache_repl', '_compile', '_compile_repl', '_expand', '_pattern_type', '_pickle', '_subx', 'compile', 'copy_reg', 'error', 'escape', 'findall', 'finditer', 'match', 'purge', 'search', 'split', 'sre_compile', 'sre_parse', 'sub', 'subn', 'sys', 'template']>>>
四、常用的Regex處理函數
4.1、re.search
re.search 函數會在字串內尋找模式比對,只到找到第一個匹配然後返回,如果字串沒有匹配,則返回None。
提示:當我們不會用模組方法的時候用help
>>> help(re.search)
search(pattern, string, flags=0)
第一個參數:規則
第二個參數:表示要匹配的字串
第三個參數:標緻位,用於控制Regex的匹配方式
執行個體:下面的例子kuangl
>>> name="Hello,My name is kuangl,nice to meet you...">>> k=re.search(r'k(uan)gl',name)>>> if k:... print k.group(0),k.group(1)... else:... print "Sorry,not search!"...kuangl uan
4.2、re.match
re.match 嘗試從字串的開始匹配一個模式,也等於說是匹配第一個單詞
>>> help(re.match)
match(pattern, string, flags=0)
第一個參數:規則
第二個參數:表示要匹配的字串
第三個參數:標緻位,用於控制Regex的匹配方式
執行個體:下面的例子匹配Hello單詞
>>> name="Hello,My name is kuangl,nice to meet you...">>> k=re.match(r"(\H....)",name)>>> if k:... print k.group(0),'\n',k.group(1)... else:... print "Sorry,not match!"...HelloHello>>>
re.match與re.search的區別:re.match只匹配字串的開始,如果字串開始不符合Regex,則匹配失敗,函數返回None;而re.search匹配整個字串,直到找到一個匹配。
4.3、re.findall
re.findall 在目標字串尋找符合規則的字串
>>> help(re.findall)findall(pattern, string, flags=0)
第一個參數:規則
第二個參數:目標字串
但三個參數:後面還可以跟一個規則選擇項
返回的結果是一個列表,建中存放的是符合規則的字串,如果沒有符合規則的字串唄找到,就會返回一個空值。
執行個體:尋找郵件帳號
>>> mail='<user01@mail.com> <user02@mail.com> user04@mail.com' #第3個故意沒有角括弧>>> re.findall(r'(\w+@m....[a-z]{3})',mail)['user01@mail.com', 'user02@mail.com', 'user04@mail.com']
4.4、re.sub
re.sub 用於替換字串的匹配項
>>> help(re.sub)
sub(pattern, repl, string, count=0)
第一個參數:規則
第二個參數:替換後的字串
第三個參數:字串
第四個參數:替換個數。預設為0,表示每個匹配項都替換
執行個體:將空白處替換成-
>>> test="Hi, nice to meet you where are you from?">>> re.sub(r'\s','-',test)'Hi,-nice-to-meet-you-where-are-you-from?'>>> re.sub(r'\s','-',test,5) #替換至第5個'Hi,-nice-to-meet-you-where are you from?'>>>
4.5、re.split
re.split 用於來分割字串
>>> help(re.split)split(pattern, string, maxsplit=0)
第一個參數:規則
第二個參數:字串
第三個參數:最大分割字串,預設為0,表示每個匹配項都分割
執行個體:分割所有的字串
>>> test="Hi, nice to meet you where are you from?">>> re.split(r"\s+",test)['Hi,', 'nice', 'to', 'meet', 'you', 'where', 'are', 'you', 'from?']>>> re.split(r"\s+",test,3) #分割前三個['Hi,', 'nice', 'to', 'meet you where are you from?']>>>
4.6、re.compile
re.compile 可以把Regex編譯成一個正則對象
>>> help(re.compile)
compile(pattern, flags=0)
第一個參數:規則
第二個參數:標誌位
執行個體:
>>> test="Hi, nice to meet you where are you from?">>> k=re.compile(r'\w*o\w*') #匹配帶o的字串>>> dir(k)['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn']>>> print k.findall(test) #顯示所有包涵o的字串['to', 'you', 'you', 'from']>>> print k.sub(lambda m: '[' + m.group(0) + ']',test) # 將字串中含有o的單詞用[]括起來Hi, nice [to] meet [you] where are [you] [from]?
>>>
五、用urllib2、re、os 模組下載檔案的指令碼
#!/usr/bin/env pythonimport urllib2import reimport osURL='http://image.baidu.com/channel/wallpaper'read=urllib2.urlopen(URL).read()pat = re.compile(r'src="http://.+?.js">')urls=re.findall(pat,read)for i in urls: url= i.replace('src="','').replace('">','')try: iread=urllib2.urlopen(url).read() name=os.path.basename(url) with open(name,'wb') as jsname: jsname.write(iread)except:
print url,"url error"