Python offers two different primitive operations based on regular expressions:

re.match() checks for a match only at the beginning of the string,

while re.search() checks for a match anywhere in the string (this is what Perl does by default).

For example:

>>> re.match('a','abc')     # Match
<_sre.SRE_Match object at 0x02B9FBB8>
>>> re.search('a','abc')    # Match
<_sre.SRE_Match object at 0x02B9F368>
>>> re.match('c','abc')     # No match
>>> re.search('c','abc')    # Match
<_sre.SRE_Match object at 0x02B9FBB8>

Regular expressions beginning with '^' can be used with search() to restrict the match at the beginning of the string:

>>> re.search('^c','abc')   # No match
>>> re.search('^a','abc') # Match <_sre.SRE_Match object at 0x02B9F368>
>>>> re.match('^c','abc') # No match
>>> re.match('^a','abc') # Match <_sre.SRE_Match object at 0x02B9FBB8>

Note however that in MULTILINE mode match() only matches at the beginning of the string, whereas using search() with a regular expression beginning with '^' will match at the beginning of each line.

>>> re.match('^X','A\nB\nX',re.MULTILINE)    # No match
>>> re.search('^X','A\nB\nX',re.MULTILINE)   # Match
<_sre.SRE_Match object at 0x02B9F368>

 

posted on 2013-04-18 17:23  101010  阅读(279)  评论(0编辑  收藏  举报