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

如何编写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 sequence con/ (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 not pop before allowing any character to be matched.
    • . matches any single character (by default, this doesn't include newlines; if you need to match newlines, add the s flag at the end: /con\/(?:(?!pop).)*\/top/s).
    • * repeats this check for every character in the middle section, ensuring "pop" never appears anywhere between con/ 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/top
    • con/single-segment/top
    • con/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" after con/)
    • 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:36:08