Regex to get substring between first and last occurence

Viewed 55

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.

4 Answers

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.

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]);
}

This regex expression will do the trick

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

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

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

^[^/]*\/((?:[^\/]+\/)*[^\/]+)\/[^\/]*$
  • ^ Start of string
  • [^/]*\/ Negated character class, optionally match any char except / and then match the first /
  • ( Capture group 1
    • (?:[^\/]+\/)* Optionally repeat matching 1+ times any char except / followed by matching the /
    • [^\/]+ Match 1+ times any char except /
  • ) Close group 1
  • \/[^\/]* Match the last / followed by optionally matching any char except /
  • $ End of string

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