marc marc - 1 month ago 7
jQuery Question

RegEx- allow alpha,numeric with only special char Comma - but no precceeding or succeeding commas

i need help in forming an regular expression that allow Alpha,Numeric and only special character comma - but comma should not be present at starting or ending or no middle blank commas..
Right now i am using the below regex which works fine for the aplha-numeric-comma , but it will allow comma at beginning or ending or blank commas.

/^[a-zA-Z0-9,]*$/ --> working regex that allows alpha-numeric-comma

so need help in regex for the above requirement of no precceeding/succeeding/blank commas in the middle...

correct case : abc,abc12,asdf,qwer23
wrong case : ,abc,abc12,asdf,qwer23
wrong case: abc,abc12,asdf,qwer23,
wrong case : abc,abc12,,asdf,qwer23

struck for the last 2 hrs in fixing this and any help is greatly appreciated..

Answer

I suggest splitting out the comma from the char class and use a * quantified group wrapping the whole expression with an optional non-capturing group around an obligatory subpattern (that requires at least 1 char) (as your regex also allows an empty string):

^(?:[a-zA-Z0-9]+(?:,[a-zA-Z0-9]+)*)?$

See the regex demo

Details:

  • ^ - start of a string
  • (?:[a-zA-Z0-9]+(?:,[a-zA-Z0-9]+)*)? - an optional sequence of (=the whole string may be empty):
    • [a-zA-Z0-9]+ - 1 or more alphanumeric
    • (?:,[a-zA-Z0-9]+)* - zero or more (due to *) sequences of:
      • , - comma
      • [a-zA-Z0-9]+ - 1 or more alphanumeric
  • $ - end of string.

JS demo:

var test = [
    "abc,abc12,asdf,qwer23", // correct 
    ",abc,abc12,asdf,qwer23", // incorrect
    "abc,abc12,asdf,qwer23,", // incorrect
    "abc,abc12,,asdf,qwer23" ]; // incorrect
var rx = /^(?:[a-zA-Z0-9]+(?:,[a-zA-Z0-9]+)*)?$/;
for (var s of test) {
  console.log(s + " => " + rx.test(s));
}