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

正则表达式需求:允许开头空格,禁止单词间出现空格

Regex for Allowing Leading Spaces but No Internal Spaces

Got it, let's craft the perfect regex for your needs! You want to allow leading spaces but block any spaces between words (or more accurately, no spaces anywhere except at the very start). Here's what you need:

Core Regex Patterns

If you require at least one non-space character (most common use case)

^\s*\S+$

If you want to allow entirely empty or all-space strings

^\s*\S*$

Let's break down how this works

  • ^: Anchors the match to the start of the string, so we don't miss leading spaces
  • \s*: Matches zero or more whitespace characters (this covers any leading spaces you're okay with—from none to dozens)
  • \S+: Matches one or more non-whitespace characters (ensures there's actual content without any spaces in it; swap this to \S* if you want to allow strings that are just spaces or completely empty)
  • $: Anchors the match to the end of the string—this is critical! It stops any spaces from sneaking in anywhere else (middle or end)

Test Cases to Verify

Valid Matches (using the first pattern)

  • hello (no leading spaces, single continuous word)
  • foo123!@# (multiple leading spaces, non-space characters including symbols)
  • x (single leading space + single character)

Invalid Matches (both patterns will reject these)

  • hello world (space between two words)
  • test 456 (multiple spaces in the middle)
  • bar (trailing space after the word)
  • abc def ghi (multiple spaces between multiple words)

That should cover exactly what you need—adjust the pattern based on whether you want to allow all-space strings or not!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:46:37