简体   繁体   English

.Net Regex for逗号分隔的字符串,格式严格

[英].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'. 或包含一个逗号分隔的字符串,该字符串必须如下所示:'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. 多少个逗号分隔的值无关紧要,但是如果字符串不为空,则它必须遵守逗号分隔的格式(并且只有逗号分隔),并且周围没有空格,并且每个值只能包含ascii az / Az ..没有特殊字符或其他任何内容。

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 [a-zA-Z]是与单个大写小写字母匹配的字符类

+ is a quantifier which matches preceding character or group 1 to many times +是一个将前一个字符或第1组匹配多次的量词

* is a quantifier which matches preceding character or group 0 to many times *是一个与前一个字符或第0组匹配多次的量词

? is a quantifier which matches preceding character or group 0 or 1 time 是与前面的字符或第0或第1时间匹配的量词

$ is end of string $是字符串的结尾

考虑使用正则表达式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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