正则表达式从路径中删除文件名 [英] regex removing filename from path

查看:102
本文介绍了正则表达式从路径中删除文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何设计一个RegEx脚本,该脚本将从路径中删除文件名?诀窍是,路径上有各种各样的扳手可以投入工作.

How could I design a RegEx script which would remove a filename from a path? The trick is, the paths have all sorts of wrenches to throw into the works.

路径可以包含:

1: "Folder1/Folder2/Folder3.1234/folder4.5678/ApplesandOranges.txt","MoreInfo","EvenMoreInfo"
2: "Folder1/Folder2/Folder3.1234/folder4.91011/","MoreInfo","EvenMoreInfo"

甚至

3: "Folder1/Folder2/Folder3.1234/folder4.5678/ApplesandOranges.zip?CatsAndDogs.txt","MoreInfo","EvenMoreInfo"

在情况1和3中,我想得出以下结论:

In cases 1 and 3, I'd like to end up with:

Folder1/Folder2/Folder3.1234/folder4.5678/

尽管如此,第二秒返回为

though, it would be acceptable for the second to return as

Folder1/Folder2/Folder3.1234/folder4.5678/ApplesandOranges.zip

尽管不是首选.

在第2种情况下,由于没有文件名,它会完全跳过该行.

In case 2, it'd just skip that line entirely as there is no filename.

有什么建议吗?

通过文本编辑器使用标准RegEx.禁止使用Java等.

Using standard RegEx via a text editor. No java use and such.

注意:路径仅是示例.可能有50个文件夹.并非总是4个文件夹

Note: The path is just an example. There could be 50 folders. It's not a mere 4 folders all of the time

推荐答案

您可以使用一个简单的正则表达式,如下所示:

You can use a simple regex like this:

(.*\/).*

工作演示

Working demo

如您所见,这个想法是通过使用(.* \/)捕获所有内容到最后一个斜杠,并丢弃其余的.* .检查上面的替换部分.

As you can see, the idea is to capture all the content to the last slash by using (.*\/) and discard the rest .*. Check the substitution section above.

这篇关于正则表达式从路径中删除文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆