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

如何用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 g flag 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:00:46