You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求匹配无首尾空格且含多连续空格字符串的Regex

Regex to Match Strings with Consecutive Spaces (No Leading/Trailing Spaces)

Perfect, I've got a regex that meets your exact needs, plus a breakdown of how it works and examples to test against.

The Regex

^(?!\s)(?=.*\s{2,})(?!.*\s$).+$

Breakdown of Each Part

Let's unpack what each segment does to ensure it hits all your rules:

  • ^(?!\s): Negative lookahead at start — guarantees the string doesn't begin with any whitespace character.
  • (?=.*\s{2,}): Positive lookahead — checks that somewhere in the string, there's at least one pair of consecutive spaces (\s{2,} matches 2+ spaces, so this covers 2, 3, or more in a row).
  • (?!.*\s$): Negative lookahead at end — makes sure the string doesn't end with whitespace.
  • .+$: Matches one or more non-newline characters, so we don't match empty strings.

Valid Test Cases (Regex Returns True)

  • "hello world" (two consecutive spaces in the middle; no leading/trailing spaces)
  • "foo bar baz" (three consecutive spaces between "foo" and "bar")
  • "a b c d" (multiple sets of consecutive spaces throughout)
  • "test123 456test" (consecutive spaces between numeric and alphabetic characters)

Invalid Test Cases (Regex Returns False)

  • " hello world" (starts with a space)
  • "hello world " (ends with a space)
  • "hello world" (only single spaces, no consecutive duplicates)
  • " hello world " (leading and trailing spaces present)
  • "" (empty string)
  • "singleword" (no spaces at all)

内容的提问来源于stack exchange,提问作者Saad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:33:31