简体   繁体   English

正则表达式可以在字符串的倒数第二次出现之前进行匹配

[英]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". 代替正则表达式,使用split并利用“切片”的优势。

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. 这个答案是针对python2的(您未指定哪种语言),在某些其他语言中也有等效的命令。 For example, java has a String.split() method (to complicate things, it requires a regular expression). 例如,java有一个String.split()方法(要使事情复杂化,它需要一个正则表达式)。 Consult the documentation for the language you are using. 请查阅文档以了解所使用的语言。

Maybe try this https://regex101.com/r/bH2vI0/1 : 也许尝试一下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. 虽然不确定sublime是否允许先行,但基本上只匹配除最后两个之外的每个word + / [Az] might be better if you don't want digits and _ 如果您不需要数字和_[Az]可能会更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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