我是正则表达式的新手,我希望从字符串末尾删除已知数量的字符。该字符串代表一个文件路径,因此我想去掉尾随字符,而不是 c:\test\test1\test2
,留下 c:\test
。
我遇到的问题是反斜杠。
我会使用哪种正则表达式来执行此操作?
最佳答案
Some people, when confronted with a problem, think "I know, I'll use regular expressions."
Now they have two problems.
由于您处理的是文件路径,因此可以使用 Path 的方法计算结果的类:
string GetPathFirstLevel(string path)
{
while (Path.GetDirectoryName(path) != Path.GetPathRoot(path))
{
path = Path.GetDirectoryName(path);
}
return path;
}
这将返回以下值:
GetPathFirstLevel(@"c:\test\test1\test2") // @"c:\test"
GetPathFirstLevel(@"c:\test") // @"c:\test"
GetPathFirstLevel(@"c:") // null
关于c# - 从路径字符串中去除尾随字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1869735/