【问题标题】:How can I find a specific string within a path using regex? [duplicate]如何使用正则表达式在路径中找到特定字符串? [复制]
【发布时间】:2018-12-28 09:13:31
【问题描述】:

我有以下路径:

/s/STRINGINEED/abcdef/

我应该如何构建我的正则表达式以匹配STRINGINEED

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

【问题讨论】:

  • '/s/STRINGINEED/abcdef/'.split('/')[2] ?
  • 使用捕获组正则表达式:'/s/STRINGINEED/abcdef/'.match(/\/s\/(.*?)\//)[1]
  • 使用后向和前向正则表达式:'/s/STRINGINEED/abcdef/'.match(/(?<=\/s\/).*?(?=\/)/)[0]

标签: javascript regex string path


【解决方案1】:

要在路径中获得/s/ 之后的string,您可以使用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]);

【讨论】:

  • @deeJ 不客气,很高兴它有帮助。
【解决方案2】:

你可以执行:

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

然后使用匹配的第一组。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    相关资源
    最近更新 更多