2010-10-20 53 views
1

我正在製作一個應用程序,將該遊戲的分辨率更改爲請求的分辨率。C#替換通配符

StreamReader reader = new StreamReader(@"C:\Documents and Settings\ARTech\Bureaublad\PersistentSymbols.ini");//Reads the file. 
string content = reader.ReadToEnd();//Puts the content of the file, into a variable. 
reader.Close(); 
string replace = "persistent extern INDEX m_pixScreenWidth=(INDEX)" + txtWidth.Text + ";"; 
content = content.Replace("persistent extern INDEX m_pixScreenWidth=(INDEX)1920;", replace);//Replaces the ScreenWidth of the game to the requested number. 
replace = "persistent extern INDEX m_pixScreenHeight=(INDEX)" + txtHeight.Text + ";"; 
content = content.Replace("persistent extern INDEX m_pixScreenHeight=(INDEX)1200;", replace);//Replaces the ScreenHeight of the game to the requested number. 

StreamWriter writer = new StreamWriter(@"C:\Documents and Settings\ARTech\Bureaublad\PersistentSymbols.ini"); 
writer.Write(content);//Saves the changes. 
writer.Close(); 

的問題是,這項決議並不總是1920×1200,所以我需要某種形式的通配符,它​​接受persistent extern INDEX m_pixScreenWidth=(INDEX);之間的一切。

回答

2

你可能想尋找到一個INI讀/寫像這樣的項目:An INI file handling class using C#。然後,您可以抓住所需的鍵並適當地設置值。

否則,你可以寫一個正則表達式像這樣:

string input = @"persistent extern INDEX m_pixScreenWidth=(INDEX)1920; 
... 
persistent extern INDEX m_pixScreenHeight=(INDEX)1200;"; 
string width = "800"; 
string height = "600"; 

string pattern = @"(persistent extern INDEX m_pixScreen(?<Type>Width|Height)=\(INDEX\))\d+;"; 
string result = Regex.Replace(input, pattern, 
        m => m.Groups[1].Value 
         + (m.Groups["Type"].Value == "Width" ? width : height) 
         + ";"); 

Console.WriteLine(result); 

模式細分:

  • (persistent extern INDEX m_pixScreen(?<Type>Width|Height)=\(INDEX\)):您預期的文本,包括高度/寬度和索引的文本,是擺在一個由開合圓括號組成的捕獲組。我們將在稍後提及。
  • (?<Type>Width|Height):一個命名的捕獲組,在寬度和高度之間交替捕獲兩者。這樣一種模式可以處理這兩種類型的文本。
  • \(INDEX\):圓括號必須從字面上進行匹配,因爲它們在正則表達式中如果未轉義(用於如上所述的分組)那樣具有特殊含義。
  • \d+\d匹配數字[0-9]+使其至少匹配一個數字(1個或多個數字)。
  • ;:此相匹配的尾隨分號

一個lambda用於與MatchEvaluator過載Replace方法。基本上,你正在建立的字符串備份。 Groups[1]指的是捕獲的第一組文本(請參見模式細分中的第一點)。接下來我們檢查指定的組Type並檢查我們是處理寬度還是高度。我們適當地替換新值。最後,我們在末尾添加分號以獲得最終替換結果。