tags:

views:

62

answers:

2
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.

+4  A: 

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.

Mark Byers
That's `/\d+(?=_)/g`. Not sure why it isn't written.
Kobi
Kobi: That was already part of the question, but he edited it out.
Mark Byers
That is so strange.
Kobi
As I mentioned my code works with look ahead strategy. My main question was why the capturing of underscore is not working in the last solution. Thanks.
Nadal
@dorelal: Updated answer. Any better?
Mark Byers
A: 

Try

var regex = /(\d+?)(_)/
Robusto