Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex comma delimited string validation

Tags:

c#

regex

I have a string that should be valid only if it has 2 characters and it is delimited by commas.

AD,AC,AN,JP (valid)
AD (valid) if user enter only one it must be validate

Must return invalid if it's a number or any other character besides comma or its length is greater than 2.

AD,12,AN,JP (invalid)
AAD,12,AN,JP (invalid)
AA,CC,ANA,JP (invalid)
AA,#C,AA,JP (invalid)
like image 476
Ali Hasan Avatar asked Jan 16 '23 06:01

Ali Hasan


1 Answers

This assumes that the input is always uppercase:

var reggie = new Regex(@"^[A-Z]{2}(,[A-Z]{2})*$");

If, on top of validating the input, you want to extract the data, you can then perform a simple split on the comma (regex split is not necessary):

if (reggie.IsMatch(inputString))
    string[] values = string.Split(',');
like image 179
Quick Joe Smith Avatar answered Jan 24 '23 18:01

Quick Joe Smith