Search code examples
regexspaces

Regex to limit the number of spaces in a text string


I am trying to establish the following but I am unable to. I need to allow no spaces at all or a maximum of 2 white spaces within my text string. Following is my regex:

/^([^\s]*\s[^\s]*){0,2}$/

The above one is partially working fine i.e. allowing 1 to max 2 spaces within my text however, its failing when there are NO SPACES at all in my text although I have defined 0 to 2.

Any help?


Solution

  • Try this:

    ^([^\s]*[\s]?[^\s]*){0,2}$
    

    [^\s]* matches a space zero or one times.