使用正则表达式查找子串:仅当子串前后均含字母时返回False
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
Falseif the substring 'at' has letters both before and after it; returnTruein 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' → returnsTrue(correct)'eat apple'has 'at' inside 'eat' (no word boundary after 'at') → no match → returnsFalse(incorrect)'he never ate maple'has 'at' inside 'ate' (no word boundary before 'at') → no match → returnsFalse(incorrect)'because he hate it'has 'at' inside 'hate' (no word boundaries) → no match → returnsFalse(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

