Javascript Regex: Why Groups With One Syntax, And Not The Other
Solution 1:
The difference is indeed with the g
modifier. When used together with .match()
it will yield all values of $0
for each match that was found.
For example:
> "This will put us on the map!".match(/(\w+)/g)
["This", "will", "put", "us", "on", "the", "map"]
But:
> "This will put us on the map!".match(/(\w+)/)
["This", "This"]
Solution 2:
string.match
will only match the string and leaves of all sub expressions. It only matches $0
.
It is meant only for matching. But if your match is inside a group, then you'll get duplicates. 1 will be the matched one and the other one will be the group.
Whereas, regex.exec
with g
modifier is used to be used in loops and the groups will be retained in the array.
To put it simply:
.match()
will only match the matched part of string without groups, an exception being is when the match itself is a group.
.exec
will give you the match, the groups.
So use .match
only when you want to find the match and use .exec
when you want the groups.
Solution 3:
Here's some perspective to clarify the point the others have made:
var str="This will put us on the map will do this!"var a=str.match(/(?:\bwill\W+)(\w+)(\W+)/g)
console.log(a);
gives you this:
["will put ", "will do "]
So when you have the g
modifier, it only does a global match for the full pattern which would normally be $0
.
It's not like e.g. php that gives you a multi-dim array of full pattern matches and grouped matches e.g.
preg_match_all('~(?:\bwill\W+)(\w+)(\W+)~',$string,$matches);
Array
(
[0] => Array
(
[0] => will put
[1] => will do
)
[1] => Array
(
[0] => put
[1] => do
)
[2] => Array
(
[0] =>
[1] =>
)
)
In javascript, you only ever get a single-dim array. So .match
will either give you each element as the match the full pattern does (with g
modifier), or else just element 0 as the full pattern match, and elements 1+ as the grouped. Whereas .exec
will only do the latter. Neither one of them will give you a multi-dim with both, like in my php example.
Post a Comment for "Javascript Regex: Why Groups With One Syntax, And Not The Other"