Merc
Merc

Reputation: 17057

Regexp to capture comma separated values

I have a string that can be a comma separated list of \w, such as:

I am trying to find a JavaScript regexp that will return ['abc123'] (first case) or ['abc123', 'def456', 'ghi789'] (without the comma).

I tried:

Is what I am trying to do even possible with regexp? I tried pretty much every combination of grouping, using capturing and non-capturing brackets, and still not managed to get this happening...

Upvotes: 4

Views: 14157

Answers (6)

Zanna
Zanna

Reputation: 676

var str = "abc123,def456, asda12, 1a2ass, yy8,ghi789";
var re = /[a-z]{3}\d{3}/g;
var list = str.match(re);
document.write("<BR> list.length: " + list.length);
for(var i=0; i < list.length; i++) {
	document.write("<BR>list(" + i + "): " +  list[i]);
}

This will get only "abc123" code style in the list and nothing else.

Upvotes: 0

Mitul Panchal
Mitul Panchal

Reputation: 632

This regex pattern separates numerical value in new line which contains special character such as .,,,# and so on.

var val = [1234,1213.1212, 1.3, 1.4]
var re = /[0-9]*[0-9]/gi;

Upvotes: 0

nhahtdh
nhahtdh

Reputation: 56809

If you want to discard the whole input when there is something wrong, the simplest way is to validate, then split:

if (/^\w+(,\w+)*$/.test(input)) {
    var values = input.split(',');

    // Process the values here
}

If you want to allow empty value, change \w+ to \w*.

Trying to match and validate at the same time with single regex requires emulation of \G feature, which assert the position of the last match. Why is \G required? Since it prevents the engine from retrying the match at the next position and bypass your validation. Remember than ECMA Script regex doesn't have look-behind, so you can't differentiate between the position of an invalid character and the character(s) after it:

something,=bad,orisit,cor&rupt
          ^^             ^^

When you can't differentiate between the 2 positions, you can't rely on the engine to do a match-all operation alone. While it is possible to use a while loop with RegExp.exec and assert the position of last match yourself, why would you do so when there is a cleaner option?


If you want to savage whatever available, torazaburo's answer is a viable option.

Upvotes: 6

user663031
user663031

Reputation:

Split on the comma first, then filter out results that do not match:

str.split(',').filter(function(s) { return /^\w+$/.test(s); })

Upvotes: 0

Timur Rahimzhanov
Timur Rahimzhanov

Reputation: 9

May be you can use split function

var st = "abc123,def456,ghi789";
var res = st.split(',');

Upvotes: -1

CMPS
CMPS

Reputation: 7769

Live demo

Try this regex :

'/([^,]+)/'

Alternatively, strings in javascript have a split method that can split a string based on a delimeter:

s.split(',')

Upvotes: 5

Related Questions