Match is a string method written as str.match(reg)
Exec is a regular expression method written as reg.exec(STR)
Both match and exec return an array when the match is successful, and null when the match is not. Therefore, before we have a thorough understanding of the rules of use of match and exec, we may mistakenly think that the use effect of the two is the same. The following are several cases to distinguish match and exec.
1. Global matching:
When global matching is not used, the matching effect is the same and only the result of the first successful match is returned:
var s = "aaa bbb ccc"; var reg = /\b\w+\b/; Var rs_match = s.match(reg); var rs_exec = reg.exec(s); console.log("match:",rs_match);
console.log("exec:",rs_exec);
Copy the code
When global matching is used, the matching results of the two are different:
var s = "aaa bbb ccc"; var reg = /\b\w+\b/g; Var rs_match1 = s.match(reg); var rs_match2 = s.match(reg); var rs_exec1 = reg.exec(s); var rs_exec2 = reg.exec(s); console.log("match1:",rs_match1);
console.log("match2:",rs_match1);
console.log("exec1:",rs_exec1);
console.log("exec2:",rs_exec2);
Copy the code
A. In a global match, match will return all matched contents; Exec matches only the content of a single match
B. If a global match is performed and multiple matches are performed, the EXE will start the match from the next bit after the last match and return the content of the match until there is no content to match, and return NULL
2. Grouping:
In the absence of global matching groups, match and exec return the same result. Since the regular expression uses parenthesis grouping, all groups of the result are returned in turn along with the matching result:
var s = "aaa1 bbb2 ccc3"; var reg = /\b(\w+)(\d{1})\b/; G var rs_match1 = s.match(reg); var rs_match2 = s.match(reg); var rs_exec1 = reg.exec(s); var rs_exec2 = reg.exec(s); console.log("match1:",rs_match1);
console.log("match2:",rs_match1);
console.log("exec1:",rs_exec1);
console.log("exec2:",rs_exec2);
Copy the code
When global matching groups, match and exec return different results. Match returns all matched results; Exec will return the result of this match. If there are groups in the expression, it will return all the groups of this match in sequence:
var s = "aaa1 bbb2 ccc3";
var reg = /\b(\w+)(\d{1})\b/g;
var rs_match1 = s.match(reg);
var rs_match2 = s.match(reg);
var rs_exec1 = reg.exec(s);
var rs_exec2 = reg.exec(s);
var rs_exec3 = reg.exec(s);
var rs_exec4 = reg.exec(s);
console.log("match1:",rs_match1);
console.log("match2:",rs_match1);
console.log("exec1:",rs_exec1);
console.log("exec2:",rs_exec2);
console.log("exec3:",rs_exec3);
console.log("exec4:",rs_exec4);
Copy the code