Search code examples
htmlregular-language

Regular expression without "Double or more" spaces


I need a regular expression that allows:

  1. You cannot put a space at the beginning and end of a line
  2. There can only be one space between words

I had enough for something like "^[АЯ-Ёа-яё0-9' ']+$", - but that's not what I need.


Solution

  • This should work:

    ^(?! )(?!.*  )(?!.* $)[^\s].*$
    

    Here's a breakdown of the expression:

    • ^: Asserts the start of the line.
    • (?! ): Negative lookahead to disallow a space at the beginning of the line.
    • (?!.* ): Negative lookahead to disallow two or more consecutive spaces within the string.
    • (?!.* $): Negative lookahead to disallow a space at the end of the line.
    • [^\s]: Match any non-whitespace character.
    • .*: Match any character (except a newline) 0 or more times.
    • $: Asserts the end of the line.

    I have put together a mini test on regex101.com.