如何用正则表达式替换包含圆括号(括号)的文本?

时间:2016-05-11 13:04:09

标签: c# .net regex string

oldvalue = "RGB = (255,000,255,000)"
newvalue = "RGB = (255,255,000,000)"
File.WriteAllText("C:\\Users\\devdrone\\Desktop\\Abc.txt", 
                    Regex.Replace(File.ReadAllText("C:\\Users\\devdrone\\Desktop\\Abc.txt"), 
                                    oldvalue, 
                                    newvalue));

这不会取代新值。

但它适用于

oldvalue = "RGB 1"
newvalue = "RGB 0"

3 个答案:

答案 0 :(得分:4)

由于您要替换的字符串是行字符串,因此不要使用Regex.Replace,而应使用String.Replace

string oldvalue = "RGB = (255,000,255,000)";
string newvalue = "RGB = (255,255,000,000)";
File.WriteAllText("C:\\Users\\devdrone\\Desktop\\Abc.txt", 
            File.ReadAllText("C:\\Users\\devdrone\\Desktop\\Abc.txt").Replace( 
                            oldvalue, 
                            newvalue));

答案 1 :(得分:0)

由于oldvalue包含在()等正则表达式中具有特殊含义的字符,因此您应使用\字符对其进行转义。

oldvalue = "RGB = \\(255,000,255,000\\)"
//or oldvalue = @"RGB = \(255,000,255,000\)"
newvalue = "RGB = (255,255,000,000)"
File.WriteAllText("C:\\Users\\devdrone\\Desktop\\Abc.txt", 
                    Regex.Replace(File.ReadAllText("C:\\Users\\devdrone\\Desktop\\Abc.txt"), 
                                    oldvalue, 
                                    newvalue));

答案 2 :(得分:0)

请尝试像这样的人:

regexp = "(.*)\((.*)\)(.*)"
newvalue = "RGB = (255,255,000,000)"
File.WriteAllText("C:\\Users\\devdrone\\Desktop\\Abc.txt",      
    Regex.Replace(File.ReadAllText("C:\\Users\\devdrone\\Desktop\\Abc.txt"), 
                                    regexp, 
                                    newvalue));