Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between RegExp’s exec() function and String’s match() function?

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?

like image 956
Justin Warkentin Avatar asked Feb 09 '12 16:02

Justin Warkentin


People also ask

What is the difference between test () and exec () methods?

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.

What is regex exec?

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.

What is difference between match and test method in JavaScript?

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.

Does string match regex?

Java - String matches() Methodmatches(regex) yields exactly the same result as the expression Pattern.


2 Answers

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.

like image 75
Ry- Avatar answered Sep 28 '22 14:09

Ry-


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.

like image 29
georg Avatar answered Sep 28 '22 16:09

georg