如何制作将提取url /adjusterAnalytics/
的第一部分的正则表达式?
没有slash
提取。
http://192.168.15.122:3000/adjusterAnalytics/individual/Xh7HTIgGw1RqnsK2TuJtiUIMahy2
欢迎任何建议。
有办法通过使用负look-behind和lazy quantifier提取所需的部分:
const [,match] = "http://192.168.15.122:3000/adjusterAnalytics/individual/Xh7HTIgGw1RqnsK2TuJtiUIMahy2".match(/(?<![\/:])\/(.*?)\//);
console.log(match)
我可能过于复杂,但我为你制作了这个正则表达式
(?<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}`);
});
}