Learn a python Regular expression for match,search,findall, A brief summary of Finditer and other functions
Here is an example of a python Regular expression using a Web page:
strhtml = "<div> <a href="/user/student/"class=" user-t "></a> </div> </div> <div class = "Navbar-search-btn visible-xs visible-sm" > <a href= "/common/mobile/search/" class= "Sch" ></a> </div> ' Print strhtml# regular expression matches such as:< a href= "xxxxx" class= "xxxx" Remod = Re.compile (r "<a href=\" ([^ \ "]*" \ "class=\" ([^\ "]*) \" ")
Example of search method
Search finds the first to find a matching string and returns
Item = Remod.search (strhtml) If item: print Item.group () Else: print "no match [Search]" # output: # <a href= "/u ser/student/"class=" User-t "
Example of Match method
Match will find the first matching string from the beginning of the string and return
Item = Remod.match (strHTML, re. M|re. S) If item: print Item.group () else:print "no match [match]" no match [match] # output # no match [match]
FindAll Examples of methods
Findall Check Find all matching strings and return a list, if there is a matching group, then it is a tuple under this list
Items = Remod.findall (strhtml) if items: print items for it in items: print Itelse: print "no match [ FindAll] "# output # [('/user/student/', ' user-t '), ('/common/mobile/search/', ' Sch ')]# ('/user/student/', ' User-t ') # ('/ common/mobile/search/', ' Sch ')
Finditer Examples of methods
Finditer Check Find all matching strings and return a groupthat can be referenced by subscript, starting with 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] "# output # 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
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Python Regular Expression summary (1)