The differences between regular expression match (), search (), and match () and search () in Python are described in detail.
Match () and search () are both regular expression matching functions in python. What are the differences between the two functions?
The match () function only checks whether the RE matches at the starting position of the string. search () scans the entire string for matching. That is to say, match () returns only when the match is successful at the zero position, if the start position is not matched successfully, match () returns none.
For example:
#! /usr/bin/env python# -*- coding=utf-8 -*-import retext = 'pythontab'm = re.match(r"\w+", text)if m: print m.group(0)else: print 'not match'
The result is: pythontab.
And:
#! /usr/bin/env python# -*- coding=utf-8 -*-#import retext = '@pythontab'm = re.match(r"\w+", text)if m: print m.group(0)else: print 'not match'
The result is not match.
Search () scans the entire string and returns the first successful match.
For example:
#! /usr/bin/env python# -*- coding=utf-8 -*-#import retext = 'pythontab'm = re.search(r"\w+", text)if m: print m.group(0)else: print 'not match'
The result is: pythontab.
In this case:
#! /usr/bin/env python# -*- coding=utf-8 -*-#import retext = '@pythontab'm = re.search(r"\w+", text)if m: print m.group(0)else: print 'not match'
The result is: pythontab.
Summary:
Regular Expression match () in Python
If we do not create a pattern object, we can use the match function to directly match the regular expression. In my opinion, this method is more concise, but it is not suitable for writing large programs, later maintenance may lead to difficulties, but some small scripts are fully competent.
Regular Expression search () function in Python
The search function and the match function are a bit similar and both can match the pattern. However, the match function and the search function are also quite different. The match function can only start matching at the starting position of the string, search can match any position of a string, but it also returns the first matching pattern. Let's take an example to understand the differences between the two.