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.