开发者

Using Regex to parse Comma Separated List

开发者 https://www.devze.com 2023-03-24 03:40 出处:网络
I have a list of specific valid values: XX,SX,FC,SC,Jump. Basically I need to look at user-supplied list of values and if one of the values does not match the above list I wil开发者_JAVA百科l throw a

I have a list of specific valid values: XX,SX,FC,SC,Jump.

Basically I need to look at user-supplied list of values and if one of the values does not match the above list I wil开发者_JAVA百科l throw an error. Can I use a regular expression to accomplish this?


This will match a comma separated list of 5 sequences of alphanumeric characters.

[A-Za-z0-9](,[A-Za-z0-9]){4}

However, and depending on the language you are using, I'd normally split the string and then check the length of the resulting array. For instance, in Java:

String csvList = "XX,SX,FC,SC,Jump";
String[] elements = csvList.split(",");
if (elements.length != 5) {
  throw new Exception();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消