如何使用正则表达式在路径中找到特定的字符串?

时间:2018-07-20 06:11:12

标签: javascript regex string path

我有以下路径:

/s/STRINGINEED/abcdef/

我应该如何构造正则表达式以使其与STRINGINEED匹配?

/s/是固定路径,所以我想获取/s/和后面的/之间的任何字符串。

2 个答案:

答案 0 :(得分:4)

要使路径中string之后的/s/,可以使用the following regex

\/s\/([\w]+)\/

演示:

const regex = /\/s\/([\w\d]+)\//gm;
const str = `/s/STRINGINEED/abcdef/`;

console.log(regex.exec(str)[1]);


另一种选择是使用 .split() method

str.split('/s/')[1].split("/")[0]

演示:

var str = '/s/STRINGINEED/abcdef/';
console.log(str.split('/s/')[1].split("/")[0]);

答案 1 :(得分:2)

您可以执行:

\/s\/([^\/]*)

,然后使用匹配的第一个组。

演示: https://regex101.com/r/MaGIlD/2