如何使用Regex仅拆分特定位置的'is',排除'What is'中的匹配
Hey there! Let's fix this regex issue for you. The problem with your current pattern (?!What)....(\sis\s) is that it’s looking four characters ahead of the "is" and only checking those don’t start with "What"—which ends up capturing the "this " before the second "is" instead of isolating just the "is" you want.
The Right Regex Approach
To target only the "is" that isn’t part of "What is", we can use a negative lookbehind to ensure the "is" isn’t immediately preceded by "What ". Here’s the regex:
(?<!What\s)\bis\b
Let’s break down what each part does:
(?<!What\s): Negative lookbehind—checks that the text right before "is" isn’t "What " (the space after "What" ensures we don’t accidentally exclude cases where "What" is followed by something else).\b: Word boundary—guarantees we’re matching the whole word "is" and not a substring of another word (like "island" or "this").is: The exact word we want to target.
Example Usage
If you want to split the string at this specific "is" (including surrounding spaces), adjust the regex to include whitespace:
(?<!What\s)\s+is\s+
In Python:
import re text = "What is this and this is cool" # Match the desired "is" matches = re.findall(r'(?<!What\s)\bis\b', text) print(matches) # Output: ['is'] # Split the string at that "is" split_result = re.split(r'(?<!What\s)\s+is\s+', text) print(split_result) # Output: ['What is this and this', 'cool']
In JavaScript:
const text = "What is this and this is cool"; // Match the desired "is" const matches = text.match(/(?<!What\s)\bis\b/g); console.log(matches); // Output: ['is'] // Split the string at that "is" const splitResult = text.split(/(?<!What\s)\s+is\s+/); console.log(splitResult); // Output: ['What is this and this', 'cool']
Note on Compatibility
Negative lookbehinds ((?<!...)) work in most modern regex flavors (Python 3.6+, JavaScript ES2018+, Java, C#, etc.). If you’re working with an older environment, we can tweak the regex to use a different approach—just let me know!
内容的提问来源于stack exchange,提问作者ViTUu

