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

求助:构建匹配以/topic结尾的URL的RegEx方案

Fixing Your Regex for URLs Ending with /topic

Hey Alex, let's get that regex working properly for you! First, let's break down why your original attempt didn't work, then share a clean, flexible solution.

What Was Wrong with Your Original Regex?

Your regex ^www.example.com/[a-zA-Z][1,]/topic$ has two key issues:

  • The [1,] syntax is invalid—you probably meant {1,} (to match one or more of the preceding character class), but even then, it only accounts for one single path segment (like /pijamas/), so it can't handle multi-level paths like /pijamas/strippedpijamas/.
  • You didn't escape the dots in www.example.com—in regex, a . matches any character, so your original regex would also match things like wwwXexampleYcom/..., which isn't what you want.

A Clean, Flexible Solution

Here's a regex that matches any URL starting with www.example.com/, followed by any number of path segments, and ending with /topic:

^www\.example\.com/(?:[^/]+/)*topic$

Let's break this down:

  • ^ anchors the match to the start of the string.
  • www\.example\.com/ matches the exact domain (dots are escaped with \ to match literal dots).
  • (?:[^/]+/)* is a non-capturing group that handles any number of path segments:
    • [^/]+ matches one or more characters that aren't a slash (this covers valid path characters like letters, numbers, hyphens, underscores, etc.).
    • / matches the trailing slash after each path segment.
    • * means this group can repeat 0 or more times (so it works for www.example.com/topic if you want that, or multi-level paths). If you want to require at least one path segment before /topic, replace * with +.
  • topic$ anchors the match to the end of the string, ensuring the URL ends exactly with topic.

Testing Examples

This regex will match:

  • www.example.com/pijamas/topic
  • www.example.com/pijamas/strippedpijamas/topic
  • www.example.com/topic (if using * in the group)

It won't match:

  • www.example.com/pijamas (doesn't end with /topic)
  • www.example.com/pijamas/topic/extra (has extra characters after topic)
  • otherdomain.com/pijamas/topic (wrong domain)

Even More Concise?

If you're working in a regex engine that supports shorthand character classes, you could replace [^/]+ with \S+ (which matches any non-whitespace character), but [^/]+ is more explicit for URL paths since it strictly excludes slashes. The version above is already as concise as it gets while remaining clear and robust.

内容的提问来源于stack exchange,提问作者alex_cargo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:44:02