简体   繁体   中英

Regex to get substring between first and last occurence

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM