Regex is not counting the white spaces inside a string

Viewed 480
  • The regex should allow any number of leading and trailing white spaces but only one white space is allowed between words
  • The string should be between 1 and 32 characters long (excluding leading and trailing white spaces, but include white spaces between the words)

My regex so far does that, except it doesn't count the white spaces between the words

^[\s]*(?:[\w]{1}[\s]?){1,32}[\s]*$

3 Answers

Use

^\s*(?=\w(?:.{0,30}\w)?\s*$)\w+(?:\s\w+)*\s*$

See the regex demo. Details:

  • ^ - start of string
  • \s* - zero or more whitespaces
  • (?=\w(?:.{0,30}\w)?\s*$) - 1 to 32 chars must be present after leading and before trailing whitespaces
  • \w+ - one or more word chars
  • (?:\s\w+)* - zero or more sequences of a whitespace and then one or more word chars
  • \s* - zero or more whitespaces
  • $ - end of string.

You can match the leading whitespace chars followed by a single word character.

Then assert 0-30 word chars followed by a word char at the right and match the optional trailing whitespace chars.

Note that \s could also match a newline.

^\s*\w(?=(?:[\w\s]{0,30}\w)?\s*$)\w*(?:\s\w+)*\s*$

The pattern matches:

  • ^ Start of string
  • \s*\w Match optional whitespace chars and a single word char
  • (?= Positive lookahead to assert that at the right is
    • (?:[\w\s]{0,30}\w)? Optionally match 0-30 occurrences of either whitspace char or word char followed by a word char
    • \s*$ Match optional whitspace chars until the end of string
  • ) Close the lookahead
  • \w*(?:\s\w+)*\s* Match an optional whitespace char (as the first is already matched) and repeat matching 1+ whitespace chars and 1+ word chars followed by trailing whitespace chars
  • $ End of string

regex demo

Looks like the following will work:

^\s*(?!.{32}\s?\w)\w+(?:\s\w+)*\s*$
  • ^ - Start string anchor.
  • \s* - 0+ Leading spaces.
  • (?!.{32}\s?\w) - Negative lookahead to prevent 32 characters followed by an optional space and a word-character.
  • \w+(?:\s\w+)* - 1+ word-characters followed by an 0+-times a non-capture group that matches a whitespace and 1+ word-chars.
  • \s* - 0+ Trailing spaces.
  • $ - End string anchor.

See the online demo

The above will force the pattern to have at least a single word-character but will fail if there is (after the leading spaces) is a sub-pattern of 32 character followed by an optional space and a word-character!

Related