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

需求:匹配结尾含单个#或#空白的正则,排除多#结尾场景

Solution for Your Regex Requirement

Let's break down your needs clearly using your provided examples first:

Valid Strings (Should Match)

  • Test-Test#
  • Test#white-space
  • Test# (implied by your rule set)
  • Test# (single # followed by whitespace, implied by your rule set)

Invalid Strings (Should NOT Match)

  • #### (all consecutive #s)
  • ####white-space (starts with consecutive #s)
  • Test### (ends with consecutive #s)
  • Test-Test###white-space (ends with consecutive #s followed by white-space)

The Correct Regex

^(?:(?!##).)*#(?:\s|white-space)?$

How It Works

Let's break down each component step by step:

  1. ^(?:(?!##).)*
    • ^ anchors the match to the start of the string
    • (?!##) is a negative lookahead that ensures no consecutive # characters exist anywhere in the string—this blocks cases like #### or Test### entirely
    • (?:...)* repeats this check for every character in the leading part of the string, allowing any valid characters (letters, hyphens, etc.) as long as there are no back-to-back #s
  2. #
    • Matches the required single trailing #—since we've already blocked consecutive #s, this guarantees it's a single, isolated # at the end of the string
  3. (?:\s|white-space)?
    • (?:...) is a non-capturing group for the optional suffix
    • \s matches any whitespace character (space, tab, newline, etc.)
    • white-space matches the literal string "white-space" exactly
    • ? makes this suffix optional, so strings ending with just a single # are also valid
  4. $ anchors the match to the end of the string, ensuring the suffix (if present) is the very last part of the string

Testing Against Your Examples

  • ####: Contains consecutive #s → No match (correct, marked invalid)
  • ####white-space: Contains consecutive #s → No match (correct, marked invalid)
  • Test###: Contains consecutive #s → No match (correct, marked invalid)
  • Test-Test###white-space: Contains consecutive #s → No match (correct, marked invalid)
  • Test-Test#: No consecutive #s, ends with single # → Match (correct, marked valid)
  • Test#white-space: No consecutive #s, ends with # + literal "white-space" → Match (correct, marked valid)

Why Your Original Regex Failed

Your original regex ^\s*\w*\S*(?:(#)(?!\1))\s?$ only checks that the final # isn't followed by another #—it doesn't block consecutive #s earlier in the string. For example, Test### would still be matched because the last # has no # after it, even though there are back-to-back #s before it. The new regex fixes this by enforcing no consecutive #s anywhere in the string.

内容的提问来源于stack exchange,提问作者Dot Net Dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:31:13