Eliminate "two or more" spaces in regular expression
P粉959676410
P粉959676410 2023-09-16 14:33:55
0
1
1008

I need a regular expression to allow:

  1. Cannot place spaces at the beginning and end of the line
  2. There can only be one space between words

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

P粉959676410
P粉959676410

reply all(1)
P粉133321839

This should work:

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

The following is a breakdown of the expression:

  • ^: Assert the beginning of the line.
  • (?! ): Negates lookahead and prohibits spaces at the beginning of the line.
  • (?!.*): Negative lookahead, two or more consecutive spaces are not allowed in the string.
  • (?!.* $): Negates lookahead and does not allow spaces at the end of the line.
  • [^\s]: Matches any non-whitespace characters.
  • .*: Matches any character (except newline) 0 or more times.
  • $: Assert the end of line.

I ran a small test on regex101.com.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template