英文:
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 = '/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
<!-- 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 = '/this/is/some/url';
const modifiedUrl = myUrl.replace(/[a-zA-Z0-9]/, 'a').replace(/^\//, '');
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
主要思想保持不变:捕获要替换的文本之前的文本,然后只匹配需要替换的内容,在替换中使用对捕获的文本的反向引用,并附加要替换的文本。
注意:如果您的替换文本包含一个字面上的$
后跟一个数字,实际上您不想将其视为反向引用,而是将其视为字面文本,您应该在上面的代码中的每个变量str1
和str2
中添加.replace(/\$/g, '$$$$')
。
英文:
You can use
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let myUrl = '/this/is/some/url';
const modifiedUrl = myUrl.replace(/\/((?:[^\/]*\/){2})[^\/]*/, '$1a');
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 = '/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
<!-- 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, '$$$$')
to each variable, str1
and str2
in the code above.
答案2
得分: 1
我会选择一种方法,将任务分为两个部分:
-
第一个替换使用正则表达式,专门针对字符串值的前导斜杠...
/^\//
...并且... -
第二个替换使用正则表达式,精确地定位到第三个路径段或路径部分...
/(?<=^(?:[^/]+\/){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 ...
/(?<=^(?:[^/]+\/){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 formxxx/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(
'this/is/some/url ...',
'this/is/some/url'
// see ... [https://regex101.com/r/jfcZBU/2]
.replace(/^\//, '')
// see ... [https://regex101.com/r/jfcZBU/1]
.replace(/(?<=^(?:[^/]+\/){2})[^/]+/, 'a')
);
console.log(
'/this/is/some/url ...',
'/this/is/some/url'
.replace(/^\//, '')
.replace(/(?<=^(?:[^/]+\/){2})[^/]+/, 'a')
);
<!-- 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(
"'this/is/some/url'.replace(regXPathCapture, '$1a') ...",
'this/is/some/url'.replace(regXPathCapture, '$1a')
);
console.log(
"'/this/is/some/url'.replace(regXPathCapture, '$1a') ...",
'/this/is/some/url'.replace(regXPathCapture, '$1a')
);
<!-- language: lang-css -->
.as-console-wrapper { min-height: 100%!important; top: 0; }
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论