用正则表达式仅替换最后一个匹配结果。

huangapple go评论53阅读模式
英文:

Replace just last matching result with regex

问题

如何只用正则表达式替换最后一个匹配结果?

示例:

path = /:demo/:demo1/:demo2
path.replace(new RegExp('/:[^/]+'), '/(?<pathinfo>[^/]+)')

如何始终只替换最后一个?

输出应该是:

/:demo/:demo1/(?<pathinfo>[^/]+)
英文:

How can I replace just last matching result with regex?

Example:

path = /:demo/:demo1/:demo2
path.replace(new RegExp(&#39;/:[^/]+&#39;), &#39;/(?&lt;pathinfo&gt;[^/]+)&#39;)

How can I always replace just last one?

Output should be:

/:demo/:demo1/(?&lt;pathinfo&gt;[^/]+)

答案1

得分: 1

function replaceLastMatch(path, regex, replacement) {
  const matches = path.match(regex);
  if (matches && matches.length > 0) {
    const lastMatch = matches[matches.length - 1];
    const lastIndex = path.lastIndexOf(lastMatch);
    return path.substring(0, lastIndex) + path.substring(lastIndex).replace(lastMatch, replacement);
  }
  return path;
}

const path = '/:demo/:demo1/:demo2';
const regex = /\/:[^/]+(?=\/|$)/g;
const replacement = '/(?<pathinfo>[^/]+)';
const result = replaceLastMatch(path, regex, replacement);
console.log(result); // 输出: /:demo/:demo1/(?<pathinfo>[^/]+)
英文:

Please try below solution this should solve your problem:

function replaceLastMatch(path, regex, replacement) {
  const matches = path.match(regex);
  if (matches &amp;&amp; matches.length &gt; 0) {
    const lastMatch = matches[matches.length - 1];
    const lastIndex = path.lastIndexOf(lastMatch);
    return path.substring(0, lastIndex) + path.substring(lastIndex).replace(lastMatch, replacement);
  }
  return path;
}

const path = &#39;/:demo/:demo1/:demo2&#39;;
const regex = /\/:[^/]+(?=\/|$)/g;
const replacement = &#39;/(?&lt;pathinfo&gt;[^/]+)&#39;;
const result = replaceLastMatch(path, regex, replacement);
console.log(result); // Output: /:demo/:demo1/(?&lt;pathinfo&gt;[^/]+)

huangapple
  • 本文由 发表于 2023年2月24日 05:29:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550502.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定