正则表达式用目录名中的下划线替换短划线而不是文件名

时间:2013-07-12 23:09:24

标签: c# regex replace

字符串示例为:

/my/test-is/for-this/to/work-right.txt

应该是:

/my/test_is/for_this/to/work-right.txt

有人想弯曲他们的Regex-Fu肌肉吗?

1 个答案:

答案 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
);