vyshnavi
vyshnavi

Reputation: 177

JavaScript regular expression for two-letter tokens separated by commas

I am trying to get the regular expression that accepts only characters with specific pattern like two characters separated by comma, but I am not able to get it.

Here i included the acceptable sting

string = ab,ca,ls,gz,tv......

I tried:

/^([a-zA-Z]{2},)|([a-zA-Z]{2})*$/ 

but it is not working as expected.

Upvotes: 1

Views: 1269

Answers (3)

Mohammad C
Mohammad C

Reputation: 1341

Try this.

/^[a-z]{2}(,[a-z]{2})*$/i

var string1 = "ab,ca,ls,gz,tv"
var string2 = "ab,c,ls"
var string3 = "ab,ca"

var regex = /^[a-z]{2}(,[a-z]{2})*$/i

document.getElementById("test").innerHTML = 
    regex.test(string1) + "<br>" + // true
    regex.test(string2) + "<br>" + // false
    regex.test(string3)            // true
<p id="test"></p>

Upvotes: 0

vallentin
vallentin

Reputation: 26167

If I'm understanding you correctly, then you're trying to get (capture) the 2 characters, with the condition that they're within the bounds of a comma or at the start or end of a line:

(?:^|,)([a-zA-Z]{2})(?=,|$)

Live preview

var string = "ab,ca,ls,gz,tv";

const regex = /(?:^|,)([a-zA-Z]{2})(?=,|$)/g;

match = regex.exec(string);

while (match != null) {
    console.log(match[1]);
    match = regex.exec(string);
}

The above outputs:

ab

ca

ls

gz

tv

Upvotes: 1

gyre
gyre

Reputation: 16777

Try using /^[a-z]{2}(?:,[a-z]{2})*$/i instead (the | inside your pattern was problematic):

var string = 'ab,ca,ls,gz,tv'

var regex = /^[a-z]{2}(?:,[a-z]{2})*$/i

console.log(regex.test(string)) //=> true

Upvotes: 3

Related Questions