使用Regex提取URL的第一个/ part /

时间:2019-04-18 14:39:19

标签: javascript regex

如何制作正则表达式来提取网址/adjusterAnalytics/的第一部分?

不使用slash进行提取。

http://192.168.15.122:3000/adjusterAnalytics/individual/Xh7HTIgGw1RqnsK2TuJtiUIMahy2

欢迎任何建议。

2 个答案:

答案 0 :(得分:1)

我可能使它复杂化了,但是我为您制作了此正则表达式

(?<schema>[a-z]+):\/\/(?<domain>[^:/]+)(?<port>:[0-9]+)\/(?<theFirstPart>[\w]+)\/.*

在js中的用法:

const regex = /(?<schema>[a-z]+):\/\/(?<domain>[^:/]+)(?<port>:[0-9]+)\/(?<theFirstPart>[\w]+)\/.*/gm;
const str = `http://192.168.15.122:3000/adjusterAnalytics/individual/Xh7HTIgGw1RqnsK2TuJtiUIMahy2`;
let m;

while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
    regex.lastIndex++;
}

// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
    console.log(`Found match, group ${groupIndex}: ${match}`);
});
}

https://regex101.com/r/IU2Ms0/2

答案 1 :(得分:1)

有一种方法可以使用负数look-behindlazy quantifier提取所需部分:

const [,match] = "http://192.168.15.122:3000/adjusterAnalytics/individual/Xh7HTIgGw1RqnsK2TuJtiUIMahy2".match(/(?<![\/:])\/(.*?)\//);

console.log(match)

相关问题