简体   繁体   中英

Regex to get match up through second to last occurrence of a string

If I have the following string:

hello/everyone/good/bye/world

I want to match everything up through the second to last forward slash:

hello/everyone/good/

But the number of slashes may vary.

What would the regex be to do this? Been googling around to no avail.

Instead of a regular expression, use split and take advantage of "slicing".

t = "hello/everyone/good/bye/world"
ts = t.split("/")
print "/".join( ts[0:-2] ) + "/"

This prints

hello/everyone/good/

This answer is for python2 (you did not specify which language), there are equivalent commands in some other languages. For example, java has a String.split() method (to complicate things, it requires a regular expression). Consult the documentation for the language you are using.

Maybe try this https://regex101.com/r/bH2vI0/1 :

((\w+\/)+(?!\w+\/\w+))

Not sure if sublime allows lookaheads though, but basically just match every word + / except for last two. [Az] might be better if you don't want digits and _

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