简体   繁体   中英

.Net Regex for Comma Separated string with a strict format

I've got a string that I need to verify for validity, the later being so if:

  • It is completely empty
  • Or contains a comma-separated string that MUST look like this: 'abc,def,ghi,jkl'.

It doesn't matter how many of these comma separated values are there, but if the string is not empty, it must adhere to the comma (and only comma) separated format with no white-spaces around them and each value may only contain ascii az/Az.. no special characters or anything.

How would I verify whether strings adhere to the rules, or not?

You can use this regex

^([a-zA-Z]+(,[a-zA-Z]+)*)?$

or

^(?!,)(,?[a-zA-Z])*$

^ is start of string

[a-zA-Z] is a character class that matches a single uppercase or lowercase alphabet

+ is a quantifier which matches preceding character or group 1 to many times

* is a quantifier which matches preceding character or group 0 to many times

? is a quantifier which matches preceding character or group 0 or 1 time

$ is end of string

考虑使用正则表达式:

bool isOK = str == "" || str.Split(',').All(part => part != "" && part.All(c=> (c>= 'a' && c<='z') || (c>= 'A' && c<='Z')));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM