Home > Article > Web Front-end > What are the specific differences between the match() and search() functions in regular expressions and the match() and search() functions?
This time I will bring you a detailed analysis and usage cases of the match(), search() functions and match() and search() functions in regular expressions. The following is a practical case. Let’s take a look.
The match() function only detects whether RE matches at the beginning of the string. search() will scan the entire string to find a match. That is to say, match() will only return if the match is successful at position 0. If If the starting position is not matched successfully, match() will return none
For example:
#! /usr/bin/env python # -*- coding=utf-8 -*- import re text = '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 re text = '@pythontab' m = re.match(r"\w+", text) if m: print m.group(0) else: print 'not match'
The result is: not match
search() will scan the entire string and return the first successful match
For example:
#! /usr/bin/env python # -*- coding=utf-8 -*- # import re text = 'pythontab' m = re.search(r"\w+", text) if m: print m.group(0) else: print 'not match'
The result is: pythontab
What about this:
#! /usr/bin/env python # -*- coding=utf-8 -*- # import re text = '@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() function in Python
If we do not create a pattern object, we can use the match function to directly perform regular expressions In my opinion, this method is more concise, but it is not suitable for writing large programs. Later maintenance may cause difficulties, but writing some small scripts is fully capable.
I believe you have mastered the methods after reading these cases. For more exciting information, please pay attention to other related articles on the php Chinese website!
Related reading:
How to use regular expressions to highlight JavaScript code
JS regular expression usage Detailed introduction
Instance introduction of regular expression form validation
The above is the detailed content of What are the specific differences between the match() and search() functions in regular expressions and the match() and search() functions?. For more information, please follow other related articles on the PHP Chinese website!