anon
anon

Reputation:

.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 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 a-z/A-z.. no special characters or anything.

How would I verify whether strings adhere to the rules, or not?

Upvotes: 1

Views: 1323

Answers (2)

Ahmed KRAIEM
Ahmed KRAIEM

Reputation: 10427

Consider not using regex:

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

Upvotes: 1

Anirudha
Anirudha

Reputation: 32817

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

+ is a quantifier which matches preceding character or group 1 to many times

* is a quantifier which matches preceding character or group 0 to many times

? is a quantifier which matches preceding character or group 0 or 1 time

$ is end of string

Upvotes: 8

Related Questions