0

I am trying to parse the following string format:

<id>:<name>[,<name>]*

As an example, consider 123:test,south-west,best,rest_well.

I wrote the following regex:

/(\d+):([a-zA-Z0-9_\-]+)(?:,([a-zA-Z0-9_\-]+))*/

My assumption was that (?:,([a-zA-Z0-9_\-]+)) would capture optional additional names (south-west, best, and rest_well). However, it only captures the last name 'rest_well'.

The printed out match:

'123:test,south-west,best,rest_well'.match(/(\d+):([a-zA-Z0-9_\-]+)(?:,([a-zA-Z0-9_\-]+))*/);
> ["123:test,south-west,best,rest_well", "123", "test", "rest_well"]

What I was expecting:

> ["123:test,south-west,best,rest_well", "123", "test", "south-west", "best", "rest_well"]

I believe other languages would actually accumulate the matched groups but somehow this fails. Maybe I am missing a small detail. Any help is appreciated!

Vadym
  • 964
  • 1
  • 13
  • 31
  • Yep, looks like it is. Too bad but I can write it differently. Just hoped for a pretty solution ;) – Vadym Jun 20 '14 at 17:15
  • The easy solution would be to split on a delimiter. See [yate's answer](http://stackoverflow.com/a/24332468/1438393). – Amal Murali Jun 20 '14 at 17:17

1 Answers1

2

Sounds like you just want to split the string with : or ,. Would this work?

var str = "123:test,south-west,best,rest_well";
var res = str.split(/:|,/);

Output

["123", "test", "south-west", "best", "rest_well"]
yate
  • 794
  • 4
  • 7
  • Hey, that's pretty sweet solution! I'd just add the following test to validate format: var re = new RegExp(/^\d+:[a-zA-Z0-9_\-]+(?:,[a-zA-Z0-9_\-]+)*$/), str = '123:test,south-west,best,rest_well', res = null; if (re.test(str)) { res = str.split(/:|,/) } else { res = []; } – Vadym Jun 20 '14 at 17:33