简体   繁体   中英

How to validate comma separated string with space using Regex

I need to validate comma separated string using regex,but I have two problem.

My sample input as follows,

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

I wrote following Regex to validate the input

^([a-z A-Z0-9 !@#$%?=*&-]+,)*[a-z A-Z0-9 !@#$%?=*&\s-]+$

First problem is when space between the commas showing as a valid string.

Eg: ERWSW1, ,   ,ERWSW2,ASA,S4

I need to avoid that, how can I do it?

And my second problem is , I also need to remove extra space from the string. two remove extra space I need function.( this is not related to above regex )

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

I need the following output,

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

Updated:

for my second problem, I wrote the following code,

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

But it's not removing spaces properly, I need this output

ERW SW1,ERW SW2,ASA

You could use a character class specifying what you would allow to match. For the spaces between the words you could use a repeating group preceded with a space.

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

Regex demo

To remove the spaces around the comma's, you could match the string including the spaces and comma *, * and then replace the comma's surrounded by spaces with a single comma.

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

Regex demo | C# demo

Code example

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

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