Python regular expressions match and search usage instances

  • 2020-04-02 14:46:20
  • OfStack

This article illustrates the use of python regular expressions match and search. Share with you for your reference. Specific analysis is as follows:

Python provides two major regular expression operations: re.match and re.search.

Match: matches the regular expression only from the beginning of the string. A successful match returns matchobject, otherwise returns none.

Search: try to match all strings of the string with the regular expression. If all strings fail to match, return none; otherwise, return matchobject. (re. Search is equivalent to the default behavior in perl)


import re
def testsearchandmatch():
 s1="helloworld, i am 30 !"
 w1 = "world"
 m1 = re.search(w1, s1)
 if m1:
 print("find : %s" % m1.group())
 if re.match(w1, s1) == none:
 print("cannot match")
 w2 = "helloworld"
 m2 = re.match(w2, s1)
 if m2:
 print("match : %s" % m2.group())
testsearchandmatch()
#find : world
#cannot match
#match : helloworld

PS: about the regular, here to provide you with 2 sites of the regular expression online tools for your reference (package regular generation, matching and verification, etc.) :

JavaScript regular expression online testing tool: (link: http://tools.jb51.net/regex/javascript)

Regular expression online generation tool: (link: http://tools.jb51.net/regex/create_reg)

I hope this article has helped you with your Python programming.


Related articles: