The match function performs the same functions as exec when the following conditions are met:
1. Regular Expressions contain grouping (parentheses)
2. Return a unique match.
See the following code:
Var str = "cat2, hat8 ";
Var p =/c (at) \ d /;
Alert(p.exe c (str ))
Alert (str. match (p ))
The message "cat2, at" is displayed. Is it strange?Now let's review the questions raised at the beginning of the article:
Var someText = "web2.0. net2.0 ";
Var pattern =/(\ w +) (\ d) \. (\ d)/g;
Var outCome_exec=pattern.exe c (someText );
Var outCome_matc = someText. match (pattern );
Analysis:
OutCome_exec value: the g attribute in pattern does not have any effect on the exec function. Therefore, exec matches the first matching string "web2.0" as the first element in the returned array, in addition, because pattern contains three groups (\ w +), (\ d), and (\ d), the array also contains three elements, followed by "web", "2", and "0". Therefore, the final result after exec execution is: ["web2.0", "web", "2 ", "0"]
OutCome_matc value: Because pattern is globally matched, match matches all strings that can be matched. Therefore, the outCome_matc value of the result array is ["web2.0", "net2.0"]. If pattern does not have the g attribute, it will be the same as the outCome_exec result, because it meets the condition described in section 4th: there are groups and a unique match is returned!
Summary:
Match is an array composed of all matching strings. However, a regular expression must specify the global g attribute to return all matching strings. If the g attribute is not specified, an array with only one element is returned.
Exec always returns information related to the first match. The returned array includes the first matched string, and the reverse reference of all groups.
-------------------------------------------
In some cases, the results returned by exec are the same as those returned by match:
Var str = "cat, hat ";
Var p =/at/; // No g attribute
Alert(p.exe c (str ))
Alert (str. match (p ))
"At" is displayed"
-------------------------------------------
In some cases, the results returned by match are the same as those returned by exec:
Var str = "cat2, hat8 ";
Var p =/c (at) \ d /;
Alert(p.exe c (str ))
Alert (str. match (p ))
"Cat2, at" is displayed"
Json2form, an industry-renowned form development framework, greatly improves the efficiency of your development of information systems. View demo