字符串示例为:
/my/test-is/for-this/to/work-right.txt
应该是:
/my/test_is/for_this/to/work-right.txt
有人想弯曲他们的Regex-Fu肌肉吗?
答案 0 :(得分:4)
不,不是真的。使用Path.GetDirectoryName
和朋友更好:
var s = "/my/test-is/for-this/to/work-right.txt";
var result = Path.Combine(
Path.GetDirectoryName(s).Replace("-", "_"),
Path.GetFileName(s)
);
如果您的路径使用/
作为目录分隔符,那么您在Windows上运行并且不希望它被\
替换,您可以随后撤消替换:
// What I 'm really doing here is showing that these constants exist;
// read the manual to see what you can expect from them.
result = result.Replace(
Path.DirectorySeparatorChar,
Path.AltDirectorySeparatorChar
);