我需要使用正则表达式验证逗号分隔的字符串,但是我有两个问题。
我的示例输入如下,
ERWSW1,ERWSW2,ASA,S4,ERWSW5,ERWSW6,ERWSW7 - Valid
ERW SW1,ERW SW2,ASA,S4,ERW SW5,ERW SW6,ERWSW7 - Valid(space between word should valid)
ERWSW1,ERWSW2,ASA,S4,ERWSW5,ERWSW6,ERWSW7, - Invalid - Comma at end
,ERWSW1,ERWSW2,ASA,S4,ERWSW5,ERWSW6,ERWSW7 - Invalid - Comma at beginning
ERWSW1,ERWSW2,,ASA,S4,ERWSW5,ERWSW6,ERWSW7 - Invalid - No value between 2,3 comma
我写了以下正则表达式来验证输入
^([a-z A-Z0-9 !@#$%?=*&-]+,)*[a-z A-Z0-9 !@#$%?=*&\s-]+$
第一个问题是逗号之间的空格显示为有效字符串。
Eg: ERWSW1, , ,ERWSW2,ASA,S4
我需要避免这种情况,我该怎么办?
我的第二个问题是,我还需要从字符串中删除多余的空间。两个删除我需要功能的多余空间。(这与上面的正则表达式无关)
Input: ERWSW1 , ERW SW2,ASA ,S4 ,ERW SW5,ERWSW6,ERWSW7
我需要以下输出,
RWSW1,ERW SW2,ASA,S4,ERW SW5,ERWSW6,ERWSW7
更新 :
对于第二个问题,我编写了以下代码,
string str = " ERW SW1 , ERW SW2 , ASA";
var ss = Regex.Replace(str, " *, *", ",");
但是它没有正确删除空格,我需要这个输出
ERW SW1,ERW SW2,ASA
您可以使用字符类来指定允许匹配的内容。对于单词之间的空格,您可以使用重复组,并在其前面加上一个空格。
^[\w!@#$%?=*&.-]+(?: [\w!@#$%?=*&.-]+)*(?:,[\w!@#$%?=*&.-]+(?: [\w!@#$%?=*&.-]+)*)*$
要删除逗号周围的空格,可以匹配包含空格和逗号的字符串 *, *
,然后用一个逗号替换逗号所包围的空格。
^ *[\w!@#$%?=*&.-]+(?: [\w!@#$%?=*&.-]+)*(?: *, *[\w!@#$%?=*&.-]+(?: [\w!@#$%?=*&.-]+)*)* *$
代码示例
string[] strings = {
"ERWSW1,ERWSW2,ASA,S4,ERWSW5,ERWSW6,ERWSW7",
"ERW SW1,ERW SW2,ASA,S4,ERW SW5,ERW SW6,ERWSW7",
"ERWSW1,ERWSW2,ASA,S4,ERWSW5,ERWSW6,ERWSW7,",
",ERWSW1,ERWSW2,ASA,S4,ERWSW5,ERWSW6,ERWSW7",
"ERWSW1,ERWSW2,,ASA,S4,ERWSW5,ERWSW6,ERWSW7",
"ERWSW1 , ERW SW2,ASA ,S4 ,ERW SW5,ERWSW6,ERWSW7",
"ERW*SW1,ERW-SW2,A.SA",
" ERWSW1 , ERWSW2 ,ASA,S4,ERWSW5 "
};
string pattern = @"^ *[\w!@#$%?=*&.-]+(?: [\w!@#$%?=*&.-]+)*(?: *, *[\w!@#$%?=*&.-]+(?: [\w!@#$%?=*&.-]+)*)* *$";
foreach (String s in strings) {
if (Regex.IsMatch(s, pattern)) {
Console.WriteLine(Regex.Replace(s, " *, *", ",").Trim());
}
}
输出量
ERWSW1,ERWSW2,ASA,S4,ERWSW5,ERWSW6,ERWSW7
ERW SW1,ERW SW2,ASA,S4,ERW SW5,ERW SW6,ERWSW7
ERWSW1,ERW SW2,ASA,S4,ERW SW5,ERWSW6,ERWSW7
ERW*SW1,ERW-SW2,A.SA
ERWSW1,ERWSW2,ASA,S4,ERWSW5
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句