I've got a string that I need to verify for validity, the later being so if:
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.