如何编写JavaScript正则:匹配首尾固定且中间不含指定字符串
Solution to Match
con/.../top Without "pop" in Between Got it, let's sort out this regex problem. Your original pattern /con\/.+\/top/ works for the basic structure, but it doesn't account for excluding strings that have "pop" in the middle—since .+ greedily matches everything up to the final /top, including any instances of "pop" along the way.
The Fixed Regex
Here's the adjusted pattern that will exclude any string with "pop" in the middle section:
const regex = /con\/(?:(?!pop).)*\/top/;
Breaking Down the Pattern
Let's walk through each part to understand how it works:
con\/: Matches the required starting sequencecon/(we escape/with\/because it's a special character in regex syntax).(?:(?!pop).)*: This is the key part that blocks "pop":(?!pop)is a negative lookahead assertion—it checks that the next three characters are notpopbefore allowing any character to be matched..matches any single character (by default, this doesn't include newlines; if you need to match newlines, add thesflag at the end:/con\/(?:(?!pop).)*\/top/s).*repeats this check for every character in the middle section, ensuring "pop" never appears anywhere betweencon/and/top.?:makes this a non-capturing group, so it doesn't store unnecessary match data.
\/top: Matches the required ending sequence/top.
Test Cases
Let's verify with your example and other scenarios:
- Matches (valid strings):
con/abc/def/topcon/single-segment/topcon/no-pop-here/top
- Does NOT match (invalid strings):
con/bottom/pop/down/top(your original test case with "pop" in the middle)con/pop/top(directly has "pop" aftercon/)con/abcpopdef/top(has "pop" embedded in a segment)
If you need case-insensitive matching, just add the i flag at the end, like /con\/(?:(?!pop).)*\/top/i.
内容的提问来源于stack exchange,提问作者Selvakumar
相关产品推荐
相关产品推荐

