Home > Software engineering >  Regex to get substring between first and last occurence
Regex to get substring between first and last occurence

Time:10-01

Assume there is the string

just/the/path/to/file.txt

I need to get the part between the first and the last slash: the/path/to

I came up with this regex: /^(.*?).([^\/]*)$/, but this gives me everything in front of the last slash.

CodePudding user response:

Don't use [^/]*, since that won't match anything that contains a slash. Just use .* to match anything:

/(.*?)\/(.*)\/(.*)/

Group 1 = just, Group 2 = the/path/to and Group 3 = file.txt.

CodePudding user response:

The regex should be \/(.*)\/. You can check my below demo:

const regex = /\/(.*)\//;
const str = `just/the/path/to/file.txt`;
let m;

if ((m = regex.exec(str)) !== null) {
    console.log(m[1]);
}

CodePudding user response:

This regex expression will do the trick

const str = "/the/path/to/the/peace";
console.log(str.replace(/[^\/]*\/(.*)\/[^\/]*/, "$1"));

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

CodePudding user response:

If you are interested in only matching consecutive parts with a single / and no //

^[^/]*\/((?:[^\/] \/)*[^\/] )\/[^\/]*$

Regex demo

const regex = /^[^/]*\/((?:[^\/] \/)*[^\/] )\/[^\/]*$/;
[
  "just/the/path/to/file.txt",
  "just/the/path",
  "/just/",
  "just/the/path/to/",
  "just/the//path/test",
  "just//",
].forEach(str => {
  const m = str.match(regex);
  if (m) {
    console.log(m[1])
  };
});

  • Related