代码之家  ›  专栏  ›  技术社区  ›  Ivar

替换通配符

  •  1
  • Ivar  · 技术社区  · 14 年前

    我正在申请将该游戏的分辨率更改为请求的分辨率。

    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 x 1200,所以我需要某种通配符,它接受介于 persistent extern INDEX m_pixScreenWidth=(INDEX) ; .

    2 回复  |  直到 7 年前
        1
  •  2
  •   Ahmad Mageed    14 年前

    您可能需要查看一个INI读写器,比如这个项目: An INI file handling class using C# . 然后您可以获取所需的键并适当地设置该值。

    否则,您可以编写这样的regex:

    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\) :括号必须转义为逐字匹配,因为它们在regex中具有特殊意义(如果未转义)(用于如上所述的分组)。
    • \d+ : \d 匹配数字 [0-9] . 这个 + 使其至少匹配一个数字(1个或多个数字)。
    • ; :这与尾随分号匹配

    lambda与 MatchEvaluator 超载 Replace 方法。从本质上说,您是在构建字符串备份。 Groups[1] 指捕获的第一组文本(见模式分解中的第一点)。接下来我们检查命名的组 Type 检查我们是在处理宽度还是高度。我们适当地替换新值。最后,我们在末尾添加分号以得到最终的替换结果。