0

字符串示例是:

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

应该:

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

有人想锻炼他们的 Regex-Fu 肌肉吗?

4

1 回答 1

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
);
于 2013-07-12T23:13:28.847 回答