求助:构建匹配以/topic结尾的URL的RegEx方案
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 likewwwXexampleYcom/..., 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 forwww.example.com/topicif 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 withtopic.
Testing Examples
This regex will match:
www.example.com/pijamas/topicwww.example.com/pijamas/strippedpijamas/topicwww.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 aftertopic)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

