3
votes

Can anyone please help me to find the suitable regular expression to validate a string that has comma separated numbers, for e.g. '1,2,3' or '111,234234,-09', etc. Anything else should be considered invalid. for e.g. '121as23' or '123-123' is invalid.

I suppose this must be possible in Flex using regular expression but I can not find the correct regular expression.


@Justin, I tried your suggestion /(?=^)(?:[,^]([-+]?(?:\d*\.)?\d+))*$/ but I am facing two issues:

  1. It will invalidate '123,12' which should be true.
  2. It won't invalidate '123,123,aasd' which is invalid.

I tried another regex - [0-9]+(,[0-9]+)* - which works quite well except for one issue: it validates '12,12asd'. I need something that will only allow numbers separated by commas.

2
Please avoid using such upper case attention getters in your questions. - Dunaril
What do you mean by "validate?" What's valid? What's not? - Matt Ball
I think each of '1', '1,2', '2,-3', '3, 4, 5', '-1 , 3' should be considered valid. - adarshr
@Ashine: I see the problem. [,^] was trying to match a literal ^ character. I've replaced it with (?:,|^) and it seems to work fine when I test it. Try the edited pattern below. - Justin Morgan

2 Answers

3
votes

Your example data consists of three decimal integers, each having an optional leading plus or minus sign, separated by commas with no whitespace. Assuming this describes your requirements, the Javascript/ActionScript/Flex regex is simple:

var re_valid = /^[-+]?\d+(?:,[-+]?\d+){2}$/;
if (re_valid.test(data_string)) {
    // data_string is valid
} else {
    // data_string is NOT valid
}

However, if your data can contain any number of integers and may have whitespace the regex becomes a bit longer:

var re_valid = /^[ \t]*[-+]?\d+[ \t]*(,[ \t]*[-+]?\d+[ \t]*)*$/;

If your data can be even more complex (i.e. the numbers may be floating point, the values may be enclosed in quotes, etc.), then you may be better off parsing the string as a CSV record and then check each value individually.

3
votes

Looks like what you want is this:

/(?!,)(?:(?:,|^)([-+]?(?:\d*\.)?\d+))*$/

I don't know Flex, so replace the / at the beginning and end with whatever's appropriate in Flex regex syntax. Your numbers will be in match set 1. Get rid of the (?:\d*\.)? if you only want to allow integers.

Explanation:

(?!,)         #Don't allow a comma at the beginning of the string.
(?:,|^)       #Your groups are going to be preceded by ',' unless they're the very first group in the string. The '(?:blah)' means we don't want to include the ',' in our match groups.
[-+]?         #Allow an optional plus or minus sign.
(?:\d*\.)?\d+ #The meat of the pattern, this matches '123', '123.456', or '.456'.
*             #Means we're matching zero or more groups. Change this to '+' if you don't want to match empty strings.
$             #Don't stop matching until you reach the end of the string.