標籤:下面運算式 findall finditer search python
學習一段pythonRegex了, 對match、search、findall、finditer等函數作一小結
下面以一段網頁為例,用pythonRegex作一個範例:
strHtml = '''<div> <a href="/user/student/" class="user-t"><img src="/uploads/avatar/2015/06/082e408c-14fc-11e5-a98d-00163e02100b_big.jpg"></a> </div> </div> <div class="navbar-search-btn visible-xs visible-sm"> <a href="/common/mobile/search/" class="sch"></a> </div>'''print strHtml#Regex 匹配如:< a href=”xxxxx” class=”xxxx”remod = re.compile(r"<a href=\"([^\"]*)\" class=\"([^\"]*)\"")
search方法舉例
search 會尋找第一個找到匹配字串並返回
item = remod.search(strHtml) if item: print item.group()else: print "no match [search]" # 輸出:# <a href="/user/student/" class="user-t"
match方法舉例
match 會從字串開頭匹配尋找第一個找到匹配字串並返回
item = remod.match(strHtml, re.M|re.S) if item: print item.group()else:print "no match [match]"no match [match] # 輸出# no match [match]
findall方法舉例
Findall查找所有找到匹配字串並返回一個列表,如果有匹配的組(group),那麼它是這個列表下的一個元組
items = remod.findall(strHtml) if items: print items for it in items: print itelse: print "no match [findall]"# 輸出# [('/user/student/', 'user-t'), ('/common/mobile/search/', 'sch')]# ('/user/student/', 'user-t')# ('/common/mobile/search/', 'sch')
finditer方法舉例
finditer查找所有找到匹配字串並返回一個group,可以通過下標引用, 下面從1開始
tems = remod.finditer(strHtml if items: for it in items: print "it.group():",it.group() print "it.group(0):",it.group(0) print "it.group(1):",it.group(1) print "it.group(2):",it.group(2)+"\n"else:print "no match [findall]"# 輸出# it.group(): <a href="/user/student/" class="user-t"# it.group(0): <a href="/user/student/" class="user-t"# it.group(1): /user/student/# it.group(2): user-t# it.group(): <a href="/common/mobile/search/" class="sch"# it.group(0): <a href="/common/mobile/search/" class="sch"# it.group(1): /common/mobile/search/# it.group(2): sch
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
PythonRegex小結(1)