使用正则表达式替换第二个正斜杠后的字符串。

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

Replace the string after second forward slash using a RegEx

问题

我想删除第一个斜杠,并将第二个斜杠后的字符串(在示例中为“some”)更改为另一个字符串,比如说“is”。结果应该是“this/is/a/url”,以下是我的代码:

let myUrl = '/this/is/some/url';
let splitUrl = myUrl.split('/').filter(v => v !== '');

splitUrl[2] = 'a';
let newUrl = splitUrl.join('/');

console.log(newUrl); // this/is/a/url

但现在我想将其转换为正则表达式,我想到了这个:

const myUrl = '/this/is/some/url';
const modifiedUrl = myUrl.replace(/[a-zA-Z0-9]/, 'a').replace(/^\//, '');

console.log(modifiedUrl); // ahis/is/some/url

但结果不是我想要的,因为它输出:ahis/is/some/url。我承认我不太擅长使用正则表达式。

一些 Stack Overflow 帖子 这里这里 没有帮助我,因为我仍然不知道如何仅替换第二个斜杠后的内容。能否得到一些帮助?

英文:

Having a string (URL path) as for example: /this/is/some/url I would like to remove the first occurrence of / and change the string after the second forward slash (in the example some) by another string let's say is. The result should be this/is/a/url and this is what I have:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let myUrl = &#39;/this/is/some/url&#39;;
let splitUrl = myUrl.split(&#39;/&#39;).filter(v =&gt; v !== &#39;&#39;);

splitUrl[2] = &#39;a&#39;;
let newUrl = splitUrl.join(&#39;/&#39;);

console.log(newUrl); // this/is/a/url

<!-- end snippet -->

But now I wanted to change that into a RegEx so I came up with this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const myUrl = &#39;/this/is/some/url&#39;;
const modifiedUrl = myUrl.replace(/[a-zA-Z0-9]/, &#39;a&#39;).replace(/^\//, &#39;&#39;);

console.log(modifiedUrl); // ahis/is/some/url

<!-- end snippet -->

But the result is not what I want since it outputs: ahis/is/some/url. I'll admit that I am not so good with RegEx.

A few SO posts here and here did not help me since I still did not get how to replace only the content after the second forward slash.

Can I get some help?

答案1

得分: 1

你可以使用以下代码:

let myUrl = '/this/is/some/url';
const modifiedUrl = myUrl.replace(/\/((?:[^\/]*\/){2})[^\/]*/, '$1a');
console.log(modifiedUrl); // this/is/a/url

查看此正则表达式演示详情

  • \/ - 斜杠字符
  • ((?:[^\/]*\/){2}) - 第1组:两个不包含斜杠的任意字符的重复 + 一个斜杠字符
  • [^\/]* - 零个或多个不包含斜杠的字符。

替换是对第1组值的反向引用,加上将插入结果字符串的新字符串。

要替换下一个URL子部分,只需将\/[^\/]*添加到正则表达式模式中:

let myUrl = '/this/is/some/url';
const str1 = 'content1';
const str2 = 'content2';
const rx = /\/((?:[^\/]*\/){2})[^\/]*\/[^\/]*/;

const modifiedUrl = myUrl.replace(rx, '$1' + str1 + '/' + str2);

console.log(modifiedUrl); // this/is/content1/content2

主要思想保持不变:捕获要替换的文本之前的文本,然后只匹配需要替换的内容,在替换中使用对捕获的文本的反向引用,并附加要替换的文本。

注意:如果您的替换文本包含一个字面上的$后跟一个数字,实际上您不想将其视为反向引用,而是将其视为字面文本,您应该在上面的代码中的每个变量str1str2中添加.replace(/\$/g, '$$$$')

英文:

You can use

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let myUrl = &#39;/this/is/some/url&#39;;
const modifiedUrl = myUrl.replace(/\/((?:[^\/]*\/){2})[^\/]*/, &#39;$1a&#39;);
console.log(modifiedUrl); // this/is/a/url

<!-- end snippet -->

See this regex demo. Details:

  • \/ - a / char
  • ((?:[^\/]*\/){2}) - Group 1: two occurrences of any zero or more chars other than / + a / char
  • [^\/]* - zero or more chars other than /.

The replacement is the backreference to the Group 1 value + the new string that will be inserted in the resulting string.

To also replace the next URL subpart, just add \/[^\/]* to the regex pattern:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let myUrl = &#39;/this/is/some/url&#39;;
const str1 = &#39;content1&#39;;
const str2 = &#39;content2&#39;
const rx = /\/((?:[^\/]*\/){2})[^\/]*\/[^\/]*/;

const modifiedUrl = myUrl.replace(rx, &#39;$1&#39; + str1 + &#39;/&#39; + str2);

console.log(modifiedUrl); // this/is/content1/content2

<!-- end snippet -->

The main idea stays the same: capture the text before the text you want to replace, then just match what you need to replace, and - in the replacement - use a backreference to the text captured, and append the text to replace with.

NOTE: If your replacement text contains a literal $ followed with a digit that you actually do not want to treat as a backreference, but as a literal text, you should add .replace(/\$/g, &#39;$$$$&#39;) to each variable, str1 and str2 in the code above.

答案2

得分: 1

我会选择一种方法,将任务分为两个部分:

  • 第一个替换使用正则表达式,专门针对字符串值的前导斜杠... /^\// ...并且...

  • 第二个替换使用正则表达式,精确地定位到第三个路径段或路径部分... /(?&lt;=^(?:[^/]+\/){2})[^/]+/。这里直接替换的方式是利用了正向后瞻,后者针对形式为xxx/yyy/的两个后续路径段的序列。

优点在于能够处理两种路径变体,无论是否有前导斜杠

在合并/混合两个正则表达式模式的情况下,也为了不必使用正向后瞻(尽管现在几乎所有相关的浏览器都支持这个功能),正则表达式会变得更复杂,因此更难阅读... /^\/*((?:[^/]+\/){2})[^/]+/

希望这有帮助。

英文:

I would choose an approach which breaks the task into two

  • where the 1st replacement uses a regex which exclusively targets a string value's leading slash ... /^\// ... and ...

  • where the 2nd replacement uses a regex which targets exactly the 3rd path-segment or path-partial ... /(?&lt;=^(?:[^/]+\/){2})[^/]+/. The direct replacement here gets achieved by utilizing a positive lookbehind, where the latter targets a sequence of two following path-segments of the form xxx/yyy/.

The advantage comes with being able of processing both path variants alike, the ones with leading slash and the ones without the latter.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

console.log(
  &#39;this/is/some/url ...&#39;,

  &#39;this/is/some/url&#39;
    // see ... [https://regex101.com/r/jfcZBU/2]
    .replace(/^\//, &#39;&#39;)
    // see ... [https://regex101.com/r/jfcZBU/1]
    .replace(/(?&lt;=^(?:[^/]+\/){2})[^/]+/, &#39;a&#39;)
);
console.log(
  &#39;/this/is/some/url ...&#39;,

  &#39;/this/is/some/url&#39;
    .replace(/^\//, &#39;&#39;)
    .replace(/(?&lt;=^(?:[^/]+\/){2})[^/]+/, &#39;a&#39;)
);

<!-- language: lang-css -->

.as-console-wrapper { min-height: 100%!important; top: 0; }

<!-- end snippet -->

In case of combining/merging both regex patterns, also in favor of not having to use a positive lookbehind (though every relevant browser meanwhile does support this feature), the regex then becomes more complex, therefore more difficult to read ... /^\/*((?:[^/]+\/){2})[^/]+/.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const regXPathCapture =
  // see ... [https://regex101.com/r/jfcZBU/3]
  /^\/*((?:[^/]+\/){2})[^/]+/;

console.log(
  &quot;&#39;this/is/some/url&#39;.replace(regXPathCapture, &#39;$1a&#39;) ...&quot;,
  &#39;this/is/some/url&#39;.replace(regXPathCapture, &#39;$1a&#39;)
);
console.log(
  &quot;&#39;/this/is/some/url&#39;.replace(regXPathCapture, &#39;$1a&#39;) ...&quot;,
  &#39;/this/is/some/url&#39;.replace(regXPathCapture, &#39;$1a&#39;)
);

<!-- language: lang-css -->

.as-console-wrapper { min-height: 100%!important; top: 0; }

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月12日 20:40:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76670653.html
匿名

发表评论

匿名网友

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

确定