如何修改正则表达式仅匹配foo序列后的w后续字符?
w-Followed Characters After foo Got it, let's fix that regex to narrow down your matches to only those after the foo substring.
The Problem with Your Original Regex
Your current regex /(?<=w)./g works great for finding every character that comes right after a w—but that includes the 3 matches before foo and the 3 you actually want after it, hence the 6 total results. We need to add a constraint to only target matches that fall after foo.
The Fixed Regex
If your regex engine supports variable-length lookbehinds (like JavaScript ES2018+, Python 3.6+, Java, etc.), use this:
/(?<=foo.*?w)./g
Breakdown of the Regex
(?<=foo.*?w): This is a positive lookbehind that checks two things:- The substring
fooexists somewhere before the current position. - After
foo, there's aw(the.*?is a non-greedy wildcard, so it stops at the nearestwinstead of skipping ahead to the last one).
- The substring
.: Matches the single character immediately following that qualifyingw.g: The global flag ensures we find all 3 matches afterfoo, not just the first one.
Example Test (JavaScript)
const inputStr = "edw a rd w o odw a rd foo edw a rd w o odw a rd"; const targetMatches = inputStr.match(/(?<=foo.*?w)./g); console.log(targetMatches); // Returns the 3 characters after w's that come after foo
Fallback for Engines Without Variable-Length Lookbehinds
If you're stuck with an older regex engine that doesn't support variable-length lookbehinds, you can split the string first to isolate the part after foo, then run your original regex on that subset:
const inputStr = "edw a rd w o odw a rd foo edw a rd w o odw a rd"; const afterFoo = inputStr.split('foo')[1]; const targetMatches = afterFoo.match(/(?<=w)./g); console.log(targetMatches); // Same 3 desired results
内容的提问来源于stack exchange,提问作者JellyRaptor

