import re help(re.compile) ''' 輸出結果為: Help on function compile in module re: compile(pattern, flags=0) Compile a regular expression pattern, returning a pattern object. 通過help可知:編譯一個正則表達式模式,返回一個模式對象。 ''' ''' 第二個參數flags是匹配模式,可以使用按位或’|’表示同時生效,也可以在正則表達式字符串中指定。 Pattern對象是不能直接實例化的,只能通過compile方法得到。匹配模式有: 1).re.I(re.IGNORECASE): 忽略大小寫 2).re.M(MULTILINE): 多行模式,改變’^’和’$’的行為 3).re.S(DOTALL): 點任意匹配模式,改變’.’的行為 4).re.L(LOCALE): 使預定字符類 \w \W \b \B \s \S 取決於當前區域設定 5).re.U(UNICODE): 使預定字符類 \w \W \b \B \s \S \d \D 取決於unicode定義的字符屬性 6).re.X(VERBOSE): 詳細模式。這個模式下正則表達式可以是多行,忽略空白字符,並可以加入注釋 ''' text="JGod is a handsome boy ,but he is a ider" print re.findall(r'\w*o\w*',text) #查找有o的單詞 #輸出結果為:['JGod', 'handsome', 'boy'] #利用compile生成一個規則模式吧,然后利用findall將某一個對象內容進行匹配。,合適則輸出符合規則的內容 regex=re.compile(r'\w*o\w*') print regex.findall(text) #>>> ['JGod', 'handsome', 'boy'] test1="who you are,what you do,When you get get there? What is time you state there?" regex1=re.compile(r'\w*wh\w*',re.IGNORECASE) wh=regex1.findall(test1) print wh #>>> ['who', 'what', 'When', 'What'] ''' re正則表達式模塊還包括一些有用的操作正則表達式的函數。下面主要介紹match函數以及search函數。 定義: re.match 嘗試從字符串的開始匹配一個模式。 原型: re.match(pattern, string, flags) 第一個參數是正則表達式,如果匹配成功,則返回一個Match,否則返回一個None; 第二個參數表示要匹配的字符串; 第三個參數是標致位,用於控制正則表達式的匹配方式,如:是否區分大小寫,多行匹配等等。 函數的返回值為真或者假。 例如:match(‘p’,’python’)返回值為真;match(‘p’,’www.python.org’)返回值為假。 定義:re.search會在給定字符串中尋找第一個匹配給定正則表達式的子字符串。 函數的返回值:如果查找到則返回查找到的值,否則返回為None。 原型: re.search(pattern, string, flags) 每個參數的含意與re.match一樣。 ''' #re.match的例子1 import re your_love=re.match("wh","What are you doing? who is you mate?",re.I) if your_love: print "you are my angle" else: print "i lose you " #相當於: print "*"*100 #便於區分 import re content="What are you doing? who is your mate?" regu_cont=re.compile("\w*wh\w*",re.I) yl=regu_cont.match(content) if yl: print yl.group(0) else: print "what happen?" 解析:首先創造了需要正則表達式匹配的字符串content; 接着利用re.compile()來創建了我們所需要的匹配規則,創建了模式對象regu_cont; yl用來接收對內容content字符串進行regu_cont正則表達式實現match函數的結果 如果有yl不為空,則使用m.group(index)輸出查找到的子字符串 否則(返回值為None) print “what happen?” match例子2 ''' match如果查找到結果, 將返回一個 MatchObject,你可以查詢 MatchObject 關於匹配字符串的相關信息了。MatchObject 實例也有幾個方法和屬性;最重要的那些如下所示: group() 返回被 RE 匹配的字符串 start() 返回匹配開始的位置 end() 返回匹配結束的位置 span() 返回一個元組包含匹配 (開始,結束) 的位置 ''' import re content="What are you doing? who is your mate?" regu_cont=re.compile("\w*wh\w*",re.I) yl=regu_cont.match(content) if yl: print yl.group(0) else: print "pass the test" print yl.group() print yl.start() print yl.end() print yl.span() 執行結果為: What What 0 4 (0, 4) #search()方法與match()方法類似 import re content='Where are you from? You look so hansome.' regex=re.compile(r'\w*som\w*') m=regex.search(content) if m: print m.group(0) else: print "Not found" #相當於: import re m=re.search(r'\w*som\w*','Where are you from? You look so handsome.',re.I) if m: print m.group(0) else: print "not found"
總結: