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

使用正则表达式查找子串:仅当子串前后均含字母时返回False

Fixing the Regex to Match Your Specific 'at' Substring Condition

Let's break down what's wrong with your original code and how to fix it to meet your requirement:

The Core Requirement

Only return False if the substring 'at' has letters both before and after it; return True in all other cases.
For your example list ['dad at home', 'eat apple', 'he never ate maple', 'because he hate it'], the expected output is [True, True, True, False].

What Was Wrong With the Original Regex

Your original pattern \bat\b uses word boundaries (\b), which only matches the standalone word 'at'. This is why you got [True, False, False, False] instead of the expected result:

  • 'dad at home' matches standalone 'at' → returns True (correct)
  • 'eat apple' has 'at' inside 'eat' (no word boundary after 'at') → no match → returns False (incorrect)
  • 'he never ate maple' has 'at' inside 'ate' (no word boundary before 'at') → no match → returns False (incorrect)
  • 'because he hate it' has 'at' inside 'hate' (no word boundaries) → no match → returns False (correct, but for the wrong reason)

The Corrected Solution

We need a regex that specifically targets 'at' when it's surrounded by letters on both sides. We can use positive lookbehind and lookahead to check for letters without including them in the match:

import re

def check_at_condition(s):
    # Match 'at' only if there's a letter before AND after it
    pattern = re.compile(r'(?<=[a-zA-Z])at(?=[a-zA-Z])')
    # If we find such a match, return False; else return True
    return not bool(pattern.search(s))

strings = ['dad at home', 'eat apple', 'he never ate maple', 'because he hate it']
result = [check_at_condition(s) for s in strings]
print(result)  # Output: [True, True, True, False]

How the Regex Works

  • (?<=[a-zA-Z]): Positive lookbehind — ensures that immediately before 'at' there is a letter (uppercase or lowercase).
  • at: The substring we're checking.
  • (?=[a-zA-Z]): Positive lookahead — ensures that immediately after 'at' there is a letter (uppercase or lowercase).

This pattern will only match 'at' in cases like 'hate' (where 'at' is between 'h' and 'e'), which is exactly the scenario where we want to return False. For all other cases (standalone 'at', 'at' at the start/end of a word, 'at' next to non-letters), the pattern won't match, so we return True.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:56:42