javascript正则表达式 - 斜杠之间的匹配

时间:2018-03-20 15:28:46

标签: javascript regex

我有一个网址:https://api.example.com/main/user1/collection1/contents/folder1/test.js

要仅捕获collection1,我尝试了以下操作,但它会随之返回user1,如何排除user1

(?:\/user1\/)[^\/]*

要仅捕获folder1/test.js,以下内容也会返回contents,我想将其排除

contents\/(.*)$

1 个答案:

答案 0 :(得分:0)

如果你想使用正则表达式。您可以尝试(?:\/user1\/)([^\/]+)仅捕获collection1

这会捕获捕获组/user1/([^\/]+)之后的部分。



const pattern = /\/user1\/([^\/]+)/;
const str = "https://api.example.com/main/user1/collection1/contents/folder1/test.js";
matches = str.match(pattern);
console.log(matches[1]);




要仅捕获folder1/test.js,您可以使用folder1\/.*$



const pattern = /folder1\/.*$/;
const str = "https://api.example.com/main/user1/collection1/contents/folder1/test.js";
matches = str.match(pattern);
console.log(matches[0]);




如果没有正则表达式,您可以使用URL



const str = "https://api.example.com/main/user1/collection1/contents/folder1/test.js";
const url = new URL(str);
const parts = url.pathname.split('/');
console.log(parts[3]);
console.log(parts[5] + '/' + parts[6]);