3.2.5.3 differences between search () and match () functions, 3.2.5.3match

Source: Internet
Author: User

3.2.5.3 differences between search () and match () functions, 3.2.5.3match

In the previously introduced regular expressions, two basic operation functions are provided: search () and match (). These two basic functions are strings matching regular expressions, but there are some differences between them in the de-matching mode, re. match is the start match of the given string header, and the match ends successfully. search starts from the given string header. If any position is matched successfully, this mode is consistent with the default method in Perl.

Example:

Print ('search () vs match ()')

Match = re. match ('C', 'abc ')

If match:

Print (match)

Else:

Print ('no Match ')

 

Match = re. search ('C', 'abc ')

If match:

Print (match)

Else:

Print ('no search ')

The output is as follows:

Search () vs match ()

No match

<_ Sre. SRE_Match object; span = (2, 3), match = 'C'>

 

Search can also use the '^' of the regular expression to restrict matching from the string header:

Match = re. search ('^ C', 'abc ')

If match:

Print (match)

Else:

Print ('no search ')

In this example, the corresponding c string is not found. In the multiline mode, match matches only the beginning of the first line, but search matches the beginning of each line, as shown in the following example:

Match = re. match ('C', 'abcd \ ncde', re. M)

If match:

Print (match)

Else:

Print ('no Match ')

Match = re. search ('^ C', 'abcd \ ncde', re. M)

If match:

Print (match)

Else:

Print ('no search ')

The output is as follows:

No match

<_ Sre. SRE_Match object; span = (5, 6), match = 'C'>

 

 

Cai junsheng QQ: 9073204 Shenzhen

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.