Regex – Regular expression to check comma separted number values in Flex

actionscript-3apache-flexregex

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.

Best Answer

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.