Viku
Viku

Reputation: 2973

regex for comma separated string (2 strings separated by comma)

I'm not good at regex, and i'm looking for a regex solution for the below comma separated string in javascript

I have a string in this format:

"string1,string2"

condition:

1 - Both string1 and string2 can contain only alphabets.
2 - Both string1 and string2 length shall not be more than 20
3 - string1 and string2 can not be empty
4 - only 2 string can be present (string1,string2,string shall be invalid)

Example ::

Edward,john = valid
Edward,  john = Invalid
12*&,john = Invalid      (shall not accept either special character or numbers)
Edward,12# = Invaid 
,          = Invalid
eeeeeeeeeeeeeeeeeeeee,jjjjjjjjjjjjjjjjjjjjj = Invalid length (more than 20)

Upvotes: 0

Views: 2581

Answers (1)

thefourtheye
thefourtheye

Reputation: 239653

  1. Both string1 and string2 can contain only alphabets.
[a-zA-Z]

The - is used to represent a range in character classes. Here we say that, it can be any alphabet between a and z or A and Z.

  1. Both string1 and string2 length shall not be more than 20
  2. string1 and string2 can not be empty
[a-zA-Z]{1,20}

It means that, match minimum 1 and maximum 20 alphabets.

  1. only 2 string can be present (string1,string2,string shall be invalid)
/^[a-zA-Z]{1,20},[a-zA-Z]{1,20}$/

^ represents the beginning of string and $ represents the end of the string.


You can check that the RegEx works fine for all your inputs mentioned in the question, like this

var invalid_cases = ['Edward,  john', '12*&,john', 'Edward,12#', ',         ',
        'eeeeeeeeeeeeeeeeeeeee,jjjjjjjjjjjjjjjjjjjjj'],
    valid_cases = ['Edward,john'],
    regEx = /^[a-zA-Z]{1,20},[a-zA-Z]{1,20}$/;

valid_cases.forEach(function(currentString) {
    console.assert(regEx.exec(currentString)[0] === currentString);
});

invalid_cases.forEach(function(currentString) {
    console.assert(regEx.exec(currentString) === null);
});

Upvotes: 5

Related Questions