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

如何构建正则表达式匹配含指定字符与空格的子串且排除单纯\s+?

Alright, let's nail this regex for you. The core requirement here is clear: we need to match strings that include at least one of your target repeated character (you used hyphens as an example) plus any amount of whitespace, but we must never match strings that are only whitespace.

Here's the regex that delivers exactly that:

^\s*-\s*(?:-\s*)*$

Let's break down each component so you understand how it works:

  • ^ and $: These are start/end anchors, ensuring we match the entire input string (not just a substring within it)
  • \s*: Matches zero or more whitespace characters (spaces, tabs, newlines—whatever your regex engine recognizes as whitespace)
  • -: The mandatory target character. This is the key guard against matching pure whitespace—if there's no hyphen present, the regex can't make a match at all
  • (?:-\s*)*: A non-capturing group that lets us match any number of additional target characters, each optionally followed by whitespace. This handles all your example cases like "- --" or "--- "

Let's verify against your test cases to confirm it works as expected:

  • ✅ Matches '-': The mandatory hyphen is present, no whitespace required
  • ✅ Matches ' -': Leading whitespace plus the required hyphen
  • ✅ Matches '- --': Hyphen, whitespace, two more hyphens with whitespace
  • ✅ Matches ' --- ': Leading whitespace, three hyphens, trailing whitespace
  • ✅ Matches '- -- --- ': All combinations of hyphens and whitespace are covered
  • ❌ Does NOT match pure whitespace (\s+): Perfect, since there's no hyphen to satisfy the mandatory match condition

If your target repeated character isn't a hyphen (say it's an underscore _, dot ., or another character), just replace all instances of - in the regex with your desired character:

^\s*_\s*(?:_\s*)*$

A quick edge case tweak: If you ever need to disallow leading/trailing whitespace (only allow whitespace between your target characters), you could adjust the regex to ^-(?:\s+-)*$, but based on your provided examples, leading and trailing whitespace is allowed, so the first regex is exactly what you need.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:19:35