If I run this:
/([^\/]+)+/g.exec('/a/b/c/d');
I get this:
["a", "a"]
But if I run this:
'/a/b/c/d'.match(/([^\/]+)+/g);
Then I get the expected result of this:
["a", "b", "c", "d"]
What's the difference?
Difference between test () and exec () methods in JavascriptTest tests for matches and returns booleans while exec captures groups and matches the regex to the input. If you only need to test an input string to match a regular expression, RegExp. test is most appropriate.
JavaScript RegExp exec() The exec() method tests for a match in a string. If it finds a match, it returns a result array, otherwise it returns null.
match() is a method on a string and takes a regex object as an argument. . test() returns a boolean if there's a match or not. It does not return what actually matches.
Java - String matches() Methodmatches(regex) yields exactly the same result as the expression Pattern.
exec
with a global regular expression is meant to be used in a loop, as it will still retrieve all matched subexpressions. So:
var re = /[^\/]+/g; var match; while (match = re.exec('/a/b/c/d')) { // match is now the next match, in array form. } // No more matches.
String.match
does this for you and discards the captured groups.
One picture is better, you know...
re_once = /([a-z])([A-Z])/ re_glob = /([a-z])([A-Z])/g st = "aAbBcC" console.log("match once="+ st.match(re_once)+ " match glob="+ st.match(re_glob)) console.log("exec once="+ re_once.exec(st) + " exec glob="+ re_glob.exec(st)) console.log("exec once="+ re_once.exec(st) + " exec glob="+ re_glob.exec(st)) console.log("exec once="+ re_once.exec(st) + " exec glob="+ re_glob.exec(st))
See the difference?
Note: To highlight, notice that captured groups(eg: a, A) are returned after the matched pattern (eg: aA), it's not just the matched pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With