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

如何编写Regex检测字符串含指定短语且两侧无额外字母数字?

Regex to Match a Phrase Without Adjacent Alphanumeric Characters

Got it, let's build the regex you need! The goal is to detect when your target phrase appears in a string, with no alphanumeric characters immediately before or after it. Here's how to do it:

The Regex Pattern

For your example phrase "apples and oranges", the regex would be:

(?<!\w)apples and oranges(?!\w)

Breakdown of the Pattern

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

  • (?<!\w): This is a negative lookbehind assertion. It checks that the character immediately before the start of your phrase is NOT an alphanumeric character (where \w matches letters, numbers, and underscores). If you want to exclude underscores specifically, replace \w with [a-zA-Z0-9].
  • apples and oranges: This is your exact target phrase—swap this out for whatever phrase you need to match.
  • (?!\w): This is a negative lookahead assertion. It checks that the character immediately after the end of your phrase is NOT an alphanumeric character.

Testing Against Your Examples

Let's verify this regex against your test cases:

Matches (Should Pass)

  • "I like apples and oranges a lot": Phrase is surrounded by spaces (non-alphanumeric) → matches
  • "apples and oranges are good for you": Phrase starts at the beginning of the string (no character before it, so the lookbehind passes) → matches
  • "You're comparing apples and oranges": Phrase ends at the end of the string (no character after it, so the lookahead passes) → matches
  • "apples and oranges.": Phrase is followed by a period (non-alphanumeric) → matches

Non-Matches (Should Fail)

  • "I like cranapples and oranges": Phrase is preceded by "cran" (alphanumeric) → lookbehind fails, no match
  • "apples and orangesherbert": Phrase is followed by "herbert" (alphanumeric) → lookahead fails, no match

Important Note for Special Characters

If your target phrase contains regex special characters (like ., *, +, ?, (, ), etc.), you'll need to escape them with a backslash (\). For example, if your phrase was "apples.oranges", the regex would become:

(?<!\w)apples\.oranges(?!\w)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:13:05