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

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

Replace just last matching result with regex

问题

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

示例:

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

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

输出应该是:

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

How can I replace just last matching result with regex?

Example:

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

How can I always replace just last one?

Output should be:

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

答案1

得分: 1

  1. function replaceLastMatch(path, regex, replacement) {
  2. const matches = path.match(regex);
  3. if (matches && matches.length > 0) {
  4. const lastMatch = matches[matches.length - 1];
  5. const lastIndex = path.lastIndexOf(lastMatch);
  6. return path.substring(0, lastIndex) + path.substring(lastIndex).replace(lastMatch, replacement);
  7. }
  8. return path;
  9. }
  10. const path = '/:demo/:demo1/:demo2';
  11. const regex = /\/:[^/]+(?=\/|$)/g;
  12. const replacement = '/(?<pathinfo>[^/]+)';
  13. const result = replaceLastMatch(path, regex, replacement);
  14. console.log(result); // 输出: /:demo/:demo1/(?<pathinfo>[^/]+)
英文:

Please try below solution this should solve your problem:

  1. function replaceLastMatch(path, regex, replacement) {
  2. const matches = path.match(regex);
  3. if (matches &amp;&amp; matches.length &gt; 0) {
  4. const lastMatch = matches[matches.length - 1];
  5. const lastIndex = path.lastIndexOf(lastMatch);
  6. return path.substring(0, lastIndex) + path.substring(lastIndex).replace(lastMatch, replacement);
  7. }
  8. return path;
  9. }
  10. const path = &#39;/:demo/:demo1/:demo2&#39;;
  11. const regex = /\/:[^/]+(?=\/|$)/g;
  12. const replacement = &#39;/(?&lt;pathinfo&gt;[^/]+)&#39;;
  13. const result = replaceLastMatch(path, regex, replacement);
  14. 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:

确定