Stack Juice2
Stack Juice2

Reputation: 77

Regex for a comma delimited string containing certain letters only

Working on creating a javascript regex that tests for this pattern: a, b, c, etc.. with certain letters.

In other words, letters separated by commas with a space after a comma. There needs to be at least one letter for the test to pass but can have an infinite amount after.

I have this so far:

/[cdefgab]+(, [cdefgab]+)*/

But am having trouble getting it to work as described.

Upvotes: 1

Views: 2016

Answers (2)

cнŝdk
cнŝdk

Reputation: 32175

If you need to have a sequence of letters separated by a comma and a space you should use this regex:

/[cdefgab](, [cdefgab])*/

In your regex there's no need for the + quantifier if it's only one letter.

THIS is a DEMO.

EDIT:

If it's meant to match exactly one letter or a sequence of letters separated with comma so you need to use the the {1} for exactly one occurence, your regex should be like this:

/[cdefgab]{1}(, [cdefgab])*/

EDIT2:

To match exactly the wanted sequence of characters and enable/disable the submit button accordingly you should use this regex /^[cdefgab]{1}(, [cdefgab])*$/) with the keyup event of the input, this a DEMO:

var validateInput = function validateInput(input) {
  var submitButton = document.getElementById("submitButton");
  if (input.value.match(/^[cdefgab]{1}(, [cdefgab])*$/)) {

    console.log("matches");
    submitButton.disabled = false;

  } else {

    console.log("Unmatches");
    submitButton.disabled = "disabled";
  }
}
Text:
<input type="text" id="txt" onkeyup="validateInput(this);" />
<input type="submit" id="submitButton" disabled/>

Upvotes: 1

Jakemmarsh
Jakemmarsh

Reputation: 4671

/[a-z](, [a-z])*/

This requires at least one letter, then can have any number of letters (0 or more) preceded by a comma and a space.

edit: if you're only looking for specific letters, replace instances of [a-z] with the letters you're looking for enclosed within square brackets. i.e. [cefg]

Upvotes: 0

Related Questions