Search code examples
regexquantifiers

Fixed quanitifer for regex with comma separated words


I have this regex for multiple words separated by comma: \w+(,\w+)*
The amount of words should be limited to exactly four, I tried the following but this didn't do the job: \w{1}(,\w+){3}

Example of valid input:
12, en_US, default, mobile

Example of invalid input:
23, en_US


Solution

  • In your regex: \w{1}(,\w+){3}, the first word is limited to one character, I guess you want:

    ^\w+(,\s*\w+){3}$
    

    where I've added anchors to match the whole line and optional spaces before the words.