Python regular expression match and search usage instance _python

Source: Internet
Author: User

This example describes the Python regular expression match and search usage. Share to everyone for your reference. The specific analysis is as follows:

Python provides the main regular expression operations in 2: Re.match and Re.search.

Match: Matches only from the beginning of the string with the regular expression, the match returns Matchobject successfully, otherwise none is returned;

Search: All string attempts to match the regular expression, if all the strings are not matched successfully, return none, otherwise return matchobject; (re.search equivalent to the default behavior in Perl)

Import re
def testsearchandmatch ():
 s1= "HelloWorld, I am!"
 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 again for you to provide 2 of this site's regular expression online tools for everyone to reference use (Baozheng generation, matching and verification, etc.):

JavaScript Regular expression on-line test tool:http://tools.jb51.net/regex/javascript

Regular Expression online generation tool:Http://tools.jb51.net/regex/create_reg

I hope this article will help you with your Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.