如何用JavaScript正则匹配多次/entry/[0-9]+并返回对应前缀字符串数组
Solution: Capture Cumulative Prefixes with Regex and
match() Absolutely! You can get the exact array you're looking for using a single regular expression combined with JavaScript's String.match() method. Here's how to do it:
Working Code Example
const inputString = '/a/b/entry/0/c/d/entry/0'; // Regex to match all cumulative paths ending with /entry/[digits] const matchRegex = /.*?\/entry\/\d+/g; const result = inputString.match(matchRegex); // Adjust to add trailing slash to the first entry (matching your example) if (result?.length) { result[0] += '/'; } console.log(result); // Output: ["/a/b/entry/0/", "/a/b/entry/0/c/d/entry/0"]
How the Regex Works
Let's break down the pattern .*?\/entry\/\d+:
.*?: The non-greedy wildcard matches any characters (except newlines) but stops at the earliest possible point. This is crucial because it ensures we capture the shortest valid path up to each/entry/[digits]instance, rather than jumping straight to the last match.\/entry\/: Escaped slashes match the literal string/entry/(slashes need escaping because they're used as regex delimiters).\d+: Matches one or more digits, which covers your[0-9]+requirement for numeric entries.- The
gflag enables global matching, so the regex scans the entire string and finds all matching cumulative paths.
Why split() Isn't Ideal
While split() is great for breaking strings into segments based on a separator, it doesn't naturally capture cumulative prefixes like we need here. Using match() with a global regex is far more direct and intuitive for this specific task.
内容的提问来源于stack exchange,提问作者user3142067
相关产品推荐
相关产品推荐

