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