Search code examples
regexdoublespaces

Regex Detect Double Space


I am trying to get a regex that will detect if there is a double space in a string. But if it does detect a double space it will return as false. So essentially anything else in the string is valid except for two spaces side by side. In the examples below the underscores (_) are spaces.

'Hello_World' ==> Valid

'Hello__World' ==> Invalid

'Hello___World' ==> Invalid

'1_2_3_4_5' ===> Valid

'1_2_3__4_5' ==> Invalid

This is my current regex

/^([^/s/s]*)$/


Solution

  • Instead of focusing on what 2 spaces isn't, use a negative look ahead for what it is:

    ^(?!.*  ).+
    

    Or if the 1st and last must be non-spaces (not stated):

    ^\S((?!.*  ).*\S)?$
    

    Which also allows exactly 1 non-space as the entire input.


    The primary thing that makes this work is this expression ^(?!.* ), which a negative look-ahead (?!.* ) anchored to start of input by ^. It asserts, without consuming input, that the text that follows the current point does not match the given expression, in this case ".* " (quotes added for clarity), which is "anything then two spaces". In other words "two spaces do not appear at any point after here".

    The second option could have been written ^\S(?!.* ).*\S$ - that same as the first but with \S at either end, but that would require different characters at each end because \S consumes input, so it wouldn't match a single letter eg "X". My making all characters other than the first optional, it allows the single character to pass (as per your requirements), while retaining the prevention of two spaces.