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

如何编写正则表达式,排除句子中目标词组前后的特定词汇关联情况?

Solution for Your Regex Matching Requirement

Let's refine your regex to handle the exclusion rules more accurately, while covering all your edge cases:

^(?!.*\bno\b\s+\b(?:text|sample text)\b)(?!.*\b(?:text|sample text)\b\s+\bnot\b).+$

Breakdown of the Regex

  • ^ and $: Anchor the match to the start and end of the string, ensuring we check the entire sentence (not just a random substring).
  • (?!.*\bno\b\s+\b(?:text|sample text)\b): Negative lookahead to exclude sentences where no (as a standalone whole word) is followed by one or more spaces, then either text or the phrase sample text (both treated as whole-word matches).
  • (?!.*\b(?:text|sample text)\b\s+\bnot\b): Second negative lookahead to exclude sentences where text or sample text (whole-word phrases) are followed by one or more spaces, then not (as a standalone whole word).
  • .+: Match any non-empty sentence that passes both lookahead exclusion checks.

Verification Against Your Examples

Let's test this against your sample scenarios:

  • ❌ Should NOT match: Sentences with no + sample text (e.g., "I have no sample text here") → The first lookahead catches the invalid pairing and excludes the sentence.
  • ❌ Should NOT match: Sentences with text + not (e.g., "This text is not what we want") → The second lookahead triggers the exclusion.
  • ❌ Should NOT match: Sentences with no, text, and not (e.g., "No text should not be included") → One of the lookaheads will detect an invalid word pairing and exclude it.
  • ✅ Should match: Sentence with only text (e.g., "This is the text we need") → No exclusion conditions are triggered, so it's a valid match.
  • ✅ Should match: Generic valid sentence (e.g., "This sentence is a valid match") → No target phrases or exclusion triggers are present, so it's matched.

Notes on Edge Cases

  • The \s+ ensures we account for one or more spaces between trigger words and target phrases (avoids false negatives from accidental word concatenation).
  • Using (?:...) for the target phrase group makes it a non-capturing group, keeping the regex efficient and avoiding unnecessary capture clutter.
  • If you need to allow for punctuation between words (e.g., "no, text"), you can adjust the regex to include optional punctuation: replace \bno\b\s+ with \bno\b[\s,.]+ to cover commas, periods, or spaces.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:00:02