2016-05-11 198 views
3
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" 
+0

你肯定也有_exact_比賽'RGB =''中Abc.txt'(255000255000)? –

+3

正則表達式中的括號有特殊含義,所以會混淆 – BugFinder

+0

@Anton yes ABC.txt中有一個完全匹配的RGB =(255,000,255,000) –

回答

4

既然你要替換的字符串是行字符串的工作,不使用Regex.ReplaceString.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)); 
+0

你是什麼意思的行字符串? –

+0

@DevDroneBhowmik好吧,我的意思是你找到的字符串不需要找到正則表達式 –

+0

那麼我應該什麼時候使用正則表達式呢? –

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)); 
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)); 
+0

這將取代'wasd()'這不是所需要的... –

相關問題