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

正则表达式中如何使用‘非’逻辑?匹配指定内容并排除特定模式

解决正则匹配需求:排除"i am from",仅匹配指定短语

Got it, let's work through this regex problem step by step. Your goal is to catch "John from" or "mr john doe from" while excluding any instances of "i am from"—here's how to get it right:

问题分析

Your original regex used a negative lookahead (?!i am from), but it was targeting the wrong position. We don't need to exclude the full "i am from" phrase upfront; instead, we need to ensure that the text immediately preceding "from" isn't "i am ".

精准解决方案

Use a negative lookbehind assertion to block the unwanted "i am " prefix, and explicitly define the phrases you want to match:

1. 匹配完整短语(含"from")

If you want the full matched strings like "John from" or "mr john doe from":

import re

text = "i am from i am text text text text i am from Japan text text John from I am mr john doe from test test test I am ..."
matches = re.findall(r"(?<!i am )(?:mr\s+john\s+doe|John)\s+from", text, re.IGNORECASE)
print(matches)
# Output: ['John from', 'mr john doe from']

2. 仅匹配前缀部分(不含"from")

If you only want the part before "from" (like "John" or "mr john doe"):

matches = re.findall(r"(?<!i am )((?:mr\s+john\s+doe|John))\s+from", text, re.IGNORECASE)
print(matches)
# Output: ['John', 'mr john doe']

关键细节解释

  • (?<!i am ): 负后顾断言,确保"from"的前面不会直接出现"i am "(末尾的空格可以避免误判类似"xi am from"这类带前缀的情况)。
  • (?:mr\s+john\s+doe|John): 非捕获组,明确指定要匹配的两种目标短语,用|分隔,避免意外匹配到其他无关文本。
  • re.IGNORECASE: 可选的忽略大小写标志,如果你需要匹配"Mr John Doe"或"john"这类大小写变体,可以保留;不需要的话直接移除即可。

灵活扩展(如需添加更多短语)

如果之后需要加入其他目标短语,比如"miss jane from",只需更新分组内容:

matches = re.findall(r"(?<!i am )(?:mr\s+john\s+doe|John|miss\s+jane)\s+from", text, re.IGNORECASE)

内容的提问来源于stack exchange,提问作者Droid-Bird

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:01:56