从文件名字符串 vb.net 中获取 \ 和 \PARTS 之间的文本

Get text between \ and \PARTS from file name string vb.net

我需要获取 \ & \PARTS 之间所有内容的值

示例:

`XamoutOFdirectorys\THIS IS WHAT I WANT\PARTS`

resulting in the text,  THIS IS WHAT I WANT

in dir1\dir2\THIS IS WHAT I WANT\PARTS

I want the text THIS IS WHAT I WANT and not dir2\THIS IS WHAT I WANT

我怎样才能做到这一点?

原因是我需要知道PARTS目录之前找到的文件名是什么,不管前后有多少个目录...

我能达到的最接近的是...

        Dim text As String = "fat\dir1\dir2\PARTS\bat"
    Dim str As String = text.Split("\"c, "\PARTS"c)(1)
    MsgBox(str)

如果你的路径变量类型是字符串。您可以在路径中找到“\PARTS”,获取路径中的起始索引 A。然后在A之前找到最后一个“\”的另一个索引B。使用子字符串函数在路径变量的范围[B,A]之间获取你想要的内容:

Dim str As String = "fat\dir1\XamoutOFdirectorys\_THIS IS WHAT I WANT\PARTS\bat"
Dim beginIdx, endIdx As Integer
endIdx = str.LastIndexOf("\PARTS") - 1
beginIdx = str.LastIndexOf("\", endIdx - 1) + 1
Dim result = str.Substring(beginIdx, endIdx - beginIdx + 1)

对了,还有正则表达式等更优雅的方法。但我真的建议你应该阅读有关 String 的 MSDN,弄脏你的手,自己获得解决方案。 Stack Overflow中也有很多关于"split path"的解决方案,你可以在了解解决方案后更改它们。最好的问候。

像这样的正则表达式:

Dim str As String = "fat\dir1\XamoutOFdirectorys\_THIS IS REALLY WHAT YOU WANT.&%+\PARTS"
Dim dir As Match = Regex.Match(str, "\([^\]+)\PARTS")
MsgBox(dir.Groups(1).ToString)

可以在现实世界中工作并支持所有可能的路径版本(在 windows 系统中测试)。

以及我的正则表达式的状态机图示

\([^\]+)\PARTS

[调试演示](https://www.debuggex.com/r/rYms5zrhWCby_FdP

尝试this

它应该 return 一个数组,每个文本都在 "\" 之间。然后可以搜索文本"PARTS",取前面的索引

Split -> [dir1, dir2, your text, PARTS]

index of PARTS = 3

index of your text = 2

我真的不知道 vb.net 但我会用任何其他语言来做到这一点。

    Dim str As String = "fat\dir1\dir2\PARTS\bat"
    Dim dir As Match = Regex.Match(str, "\([A-Za-z0-9\-]+)\PARTS")
    MsgBox(dir.Groups(1).ToString)