PythonRegex小結(1)

來源:互聯網
上載者:User

標籤:下面運算式   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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.