繁体   English   中英

如何使用正则表达式验证带空格的逗号分隔字符串

[英]How to validate comma separated string with space using Regex

我需要使用正则表达式验证逗号分隔的字符串,但我有两个问题。

我的示例输入如下,

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

我需要避免这种情况,我该怎么做?

我的第二个问题是,我还需要从字符串中删除多余的空间。 两个删除多余的空间我需要function。(这与上面的正则表达式无关

Input: ERWSW1 ,  ERW SW2,ASA ,S4 ,ERW SW5,ERWSW6,ERWSW7

我需要以下output,

RWSW1,ERW SW2,ASA,S4,ERW SW5,ERWSW6,ERWSW7

更新:

对于我的第二个问题,我编写了以下代码,

string str = " ERW SW1 , ERW SW2 , ASA";
var ss = Regex.Replace(str, " *, *", ",");

但它没有正确删除空格,我需要这个 output

ERW SW1,ERW SW2,ASA

您可以使用字符 class 指定您允许匹配的内容。 对于单词之间的空格,您可以使用前面带有空格的重复组。

^[\w!@#$%?=*&.-]+(?: [\w!@#$%?=*&.-]+)*(?:,[\w!@#$%?=*&.-]+(?: [\w!@#$%?=*&.-]+)*)*$

正则表达式演示

要删除逗号周围的空格,您可以匹配包含空格和逗号*, *的字符串,然后用单个逗号替换由空格包围的逗号。

^ *[\w!@#$%?=*&.-]+(?: [\w!@#$%?=*&.-]+)*(?: *, *[\w!@#$%?=*&.-]+(?: [\w!@#$%?=*&.-]+)*)* *$

正则表达式演示| C# 演示

代码示例

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());
    }
}

Output

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

暂无
暂无

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

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