Home > front end >  Regex max string length between commas but ignores whitespace
Regex max string length between commas but ignores whitespace

Time:04-09

I am trying to set the max string length between commas to 4.

I am using ^([^,?]{0,4},)*[^,?]{0,4}$, which works fine. However if the user adds a space before the word, the current code counts that whitespace.

Example: 'this','will','be','fine'. <-- this works.

'this',' will','not','work' <-- this does Not work. Notice the whitespace before the ' will'. How do I modify my regex to not count this whitespace?

CodePudding user response:

You can use

Validators.pattern('\\s*[^\\s,?]{0,4}(?:\\s*,\\s*[^\\s,?]{0,4})*\\s*')
Validators.pattern(/^\s*[^\s,?]{0,4}(?:\s*,\s*[^\s,?]{0,4})*\s*$/)

See the regex demo. Adjust the pattern by removing \s* anywhere you see fit.

Whenever you see a regex matches in the regex101.com tester and does not work in your code, always check the Code generator page link. See the Regex not working in Angular Validators.pattern() while working in online regex testers and Regular expression works on regex101.com, but not on prod.

Details:

  • ^ - start of string
  • \s* - zero or more whitespacs
  • [^\s,?]{0,4} - zero to four chars other than whitespace, comma and a question mark
  • (?:\s*,\s*[^\s,?]{0,4})* - zero or more sequences of a comma enclosed with zero or more whitespaces followed with zero to four chars other than whitespace, comma and a question mark
  • \s* - zero or more whitespaces
  • $ - end of string
  • Related