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

如何编写正则表达式排除完整字符串而非子串(排除"sup"示例)

Fixing Your Regex to Block Only the Exact Word "sup"

Hey there! Let's sort out that regex problem you're stuck on. First off, your current attempt [^(?!sup).*$] isn't working because it's using a negated character class ([^...]) incorrectly—those only target individual characters, not full word patterns, so it's totally missing the mark for what you need.

Let's break down your requirement clearly: you want to block only the exact, standalone word "sup", while allowing all other strings—including those that have "sup" as a substring (like "supreme" or "pusup") or don't include it at all (like "su" or "pus"). Here are the correct solutions depending on your exact use case:

Case 1: Block only strings that are exactly "sup"

If you just need to reject the string when it's precisely "sup" (and allow everything else), use this regex:

^(?!sup$).+$

How it works:

  • ^ anchors the match to the start of the string
  • (?!sup$) is a negative lookahead that checks: "from this point to the end of the string, is it NOT exactly 'sup'?"
  • .+ matches one or more of any character (swap to .* if you want to allow empty strings)

Test examples:

  • ❌ "sup" → gets blocked (doesn't match)
  • ✅ "su" → allowed (matches)
  • ✅ "supreme" → allowed (matches)
  • ✅ "pus" → allowed (matches)

Case 2: Block standalone "sup" words within longer text

If you need to reject any text where "sup" appears as a separate word (e.g., "Hey sup!" gets blocked, but "Hey supreme!" is allowed), use word boundaries:

^(?!.*\bsup\b).*$

How it works:

  • \b is a word boundary—this ensures "sup" isn't part of a longer word
  • (?!.*\bsup\b) checks that nowhere in the string does a standalone "sup" exist
  • .* matches any length of text (including empty strings if needed)

Test examples:

  • ❌ "sup" → blocked
  • ❌ "Hello sup there" → blocked
  • ✅ "Hello supreme there" → allowed
  • ✅ "pusup123" → allowed (since "sup" isn't a standalone word)

Quick code example (JavaScript)

Here's how you'd use the first regex in practice:

const blockExactSup = /^(?!sup$).+$/;

console.log(blockExactSup.test("sup")); // false (blocked)
console.log(blockExactSup.test("su")); // true (allowed)
console.log(blockExactSup.test("supreme")); // true (allowed)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:42:33