简体   繁体   English

正则表达式,用于在目录名而不是文件名中用下划线替换破折号

[英]Regex for replacing dashes with underscores in directory names and not the filenames

The string example is: 字符串示例为:

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

should be: 应该:

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

Anyone want to flex their Regex-Fu muscles? 任何人都想展示自己的Regex-Fu肌肉吗?

No, not really. 不,不是。 It's much better to use Path.GetDirectoryName and friends: 最好使用Path.GetDirectoryName和朋友:

var s = "/my/test-is/for-this/to/work-right.txt";
var result = Path.Combine(
     Path.GetDirectoryName(s).Replace("-", "_"),
     Path.GetFileName(s)
);

If your path uses / as the directory separator, you are running on Windows and you don't want it to be replaced by \\ you can simply undo the replacement afterwards: 如果您的路径使用/作为目录分隔符,则说明您正在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
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM