search

Home  >  Q&A  >  body text

Eliminate "two or more" spaces in regular expression

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粉959676410P粉959676410472 days ago1014

reply all(1)I'll reply

  • P粉133321839

    P粉1333218392023-09-17 12:55:12

    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.

    reply
    0
  • Cancelreply