1

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?

Pd1234
  • 29
  • 5
  • Do you want to match non-whitespace only comma/question mark separated entities? `^[^\s,?]{0,4}(?:,\s*[^\s,?]{0,4})*$`? – Wiktor Stribiżew Apr 08 '22 at 14:44
  • I tried your code but it does not work unfortunately. I just want to ignore the space before a word and not count it toward the max length. So 'will' = 4 chars. But ' will' = 5 chars. I want ' will' to be considered 4 chars since it should ignore the space. Note that the words are separated by commas.. – Pd1234 Apr 08 '22 at 14:51
  • Why didn't it work? What did you test it against? I assumed the words do not have whitespaces. Do you mean you also want to allow leading/trailing whitespace? Like `^\s*[^\s,?]{0,4}(?:\s*,\s*[^\s,?]{0,4})*\s*$`? – Wiktor Stribiżew Apr 08 '22 at 14:56
  • I added 'Hi, hows' to my form. It failed because it is counting hows as 5 chars instead of 4. – Pd1234 Apr 08 '22 at 15:00
  • With [my regex](https://regex101.com/r/9WkAR5/1), it matches. With [your regex](https://regex101.com/r/9WkAR5/2), it does not match. So, if my regex does not work, does it mean your regex is fine? – Wiktor Stribiżew Apr 08 '22 at 15:02
  • Yours works fine in the regex101 test env, but when i use it in my formcontrol Validators.pattern, it doesnt work for some reason. Hmmm.. – Pd1234 Apr 08 '22 at 15:51
  • That means you are not using *my* pattern. It looks like `'\\s*[^\\s,?]{0,4}(?:\\s*,\\s*[^\\s,?]{0,4})*\\s*'` or `/^\s*[^\s,?]{0,4}(?:\s*,\s*[^\s,?]{0,4})*\s*$/` in the code. See https://stackoverflow.com/a/56098660/3832970 – Wiktor Stribiżew Apr 08 '22 at 17:37

1 Answers1

0

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
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563