-2

How to make regex which will extract this first part of url /adjusterAnalytics/?

Extract without slash.

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

Any advice is welcome.

Mark James
  • 338
  • 4
  • 15
  • 43

2 Answers2

1

I overcomplicated it probably, but I made this regex for you

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

Usage within 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

online Thomas
  • 8,864
  • 6
  • 44
  • 85
1

There is way to extract the required part by using negative look-behind and a lazy quantifier:

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

console.log(match)
antonku
  • 7,377
  • 2
  • 15
  • 21