例如,我的正则表达式找到了字符串:some\file\path.xml
,我希望将其更改为new_root\some\file\path.xml
。有没有办法使用正则表达式替换方法?如果没有,那么首选方法是什么?
答案 0 :(得分:5)
看来你可以使用Regex.Replace做你想问的事。 查看MSDN上的Substitutions in Regular Expressions文章。
示例:
var path = @"C:\some\file\path.xml";
var result = Regex.Replace(path, @"(C:\\)(.*)", "$1new_root\\$2");
结果是C:\ new_root \ some \ file \ path.xml。
答案 1 :(得分:0)
你不需要正则表达式,只需使用buid-in函数找到你想要的字符串并连接你想要的东西。
对于更一般的搜索/替换,您可以这样做:
string pattern = @"(?>\w+\\)+\w+.xml";
string replacement = "new_root\\$0";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);