I'm working with some code that uses the regex /(@\w ) ?/g
for matching tagged mentions
This will match the following text returning the groups correctly without the additional space
testing
@one
and@two
and@three
If I remove the optional space ?
the regex /(@\w )/g
appears to return the same matching groups - for the above example and any other test strings I've tried
Is there some subtle difference or edge case that I might be missing between these two version of the regex?
CodePudding user response:
If there is a space the regex will match it, but it won't affect the matching groups because the space isn't in any group. Only the whole match will have the space.
console.log(...'testing @one and @two and @three'.matchAll(/(@\w ) ?/g));
// [ "@one ", "@one" ]
// [ "@two ", "@two" ]
// [ "@three", "@three" ]
The first element of each result array is the whole match and the second element is what is matched by the group (@\w )
.