使用Regex提取第一个/部分/ url

问题描述 投票:-2回答:2

如何制作将提取url /adjusterAnalytics/的第一部分的正则表达式?

没有slash提取。

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

欢迎任何建议。

javascript regex
2个回答
1
投票

有办法通过使用负look-behindlazy quantifier提取所需的部分:

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

console.log(match)

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

© www.soinside.com 2019 - 2024. All rights reserved.