1

My input looks like this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. _4,7,13 Nullam suscipit orci sit amet feugiat facilisis. Curabitur eget 8 ligula malesuada, vehicula 3,6 quam sit amet, _5 tempor velit.

I need to capture every number that's in a comma-separated list preceded by _, individually and using a single regex.

In other words, I need the bolded numbers above:

[4, 7, 13, 5]

I've been trying again and again to make this work without success. I'd like to know if this is even possible before forfeiting and going with multiple expressions.

I'm looking for a solution in Javascript, but obviously any pointer will help.

3
  • But 5 isn't in a comma-separated list... Commented Oct 21, 2014 at 15:26
  • Can you show us what you have tried? A jsfiddle would be even better. Commented Oct 21, 2014 at 15:38
  • @Evilzebra I haven't posted what I've tried because frankly, I couldn't really get much farther than a basic expression. Here is the closest I got to the requirement though (I'm still capturing that 6 in the second list): regex101.com/r/nX9hP9/2 Commented Oct 21, 2014 at 15:55

2 Answers 2

1

You can use this code in Javascript:

var input = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. 4,7,13 Nullam suscipit orci sit amet feugiat facilisis. Curabitur eget 8 ligula malesuada, vehicula 3,6 quam sit amet, 5 tempor velit.';

var matches = [];
input.replace(/_(\d+(?:,\d+)*)\b/g, function($0, $1) { 
      matches = matches.concat( $1.split(/,/g) ); return $1; } );

console.log(matches);
//=> ["4", "7", "13", "5"]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the detailed answer. That seems to be the most efficient way to do it. I wanted to make sure that capturing the numbers through the regex alone wasn't possible before doing it "manually".
I believe there is no alternative other than using a callback function like this.
0
(_\d+(?:,\d+)*)

Try this.Grab the captures.Then split by ,.See demo.

http://regex101.com/r/rQ6mK9/23

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.