string = 'Hello 1234_ world 4567_ trap 456';
I need to capture all digits followed by underscore. Following code will do.
string.match(/(\d+?)(_)/gi);
However I tested following code and it worked except that underscore was also being captured.
(\d+)_
So I decided to give underscore its own capture group like this
(\d+)(_)
But it did not work. I am getting digits with trailing underscore. I do not want underscore.
The match method returns a string containing the characters that matched regardless of whether or not they were part of a (capturing or non-capturing) group.
The
(?=_)group is a lookahead. A lookahead is a zero-width match and therefore it doesn’t match any characters. It matches the empty string, but only if the character immediately afterwards is an underscore.The groups are not really the important thing here. When you use a zero-width match, the result won’t include any extra characters.