简体   繁体   English

C# 正则表达式获取两个标签之间的文本?

[英]C# Regex to get text between two tags?

Alright, I'm having a bit of difficulty replacing text in this config file.好的,我在替换此配置文件中的文本时遇到了一些困难。 The section I'm trying to replace...我正在尝试替换的部分...

    <!-- Executables we want to manage -->
  <KioskExecutables>
    <Executables>
      <add appName="Valet" exeName="365Valet.exe" startOrder="0" />
      <add appName="Sync" exeName="365Sync.exe" startOrder="1" />
      <add appName="Readiness" exeName="KioskReadiness.exe" startOrder="2" />
</Executables>
  </KioskExecutables>

I would like to swap out the text between the tags.我想换掉标签之间的文本。 I wrote the following..我写了以下..

string matchCodeTag = @"<Executables>(.*?)</Executables>";
string textToReplace = File.ReadAllText(@"C:\Temp\Controller.exe.config");
string replaceWith = "<add appName=\"Disable\" exeName=\"C:\\Temp\\Disable.exe\" startOrder=\"0\" />";
string output = Regex.Replace(textToReplace, matchCodeTag, replaceWith);

It doesn't seem to be picking up the match though, I believe because the newline characters but I'm not certain.不过,它似乎并没有得到匹配,我相信是因为换行符,但我不确定。

Could someone push me in the right direction?有人能把我推向正确的方向吗?

As commented, you should use an XmlDocument to parse your config.正如所评论的,您应该使用XmlDocument来解析您的配置。

But if you must use regex you need to enable the Singleline option so that the dot character (.) matches newline characters as well eg但是,如果您必须使用正则表达式,则需要启用 Singleline 选项,以便点字符 (.) 也与换行符匹配,例如

string matchCodeTag = @"<Executables>(.*)</Executables>";
string textToReplace = File.ReadAllText(@"C:\Temp\Controller.exe.config");
string replaceWith = "<add appName=\"Disable\" exeName=\"C:\\Temp\\Disable.exe\" startOrder=\"0\" />";
string output = Regex.Replace(textToReplace, matchCodeTag, 
                              replaceWith, RegexOptions.Singleline);

or you can set the option in the regex pattern like this或者您可以像这样在正则表达式模式中设置选项

string matchCodeTag = @"(?s)<Executables>(.*)</Executables>";

Your pattern does not need the question mark as the * is already "zero or more matches"您的模式不需要问号,因为 * 已经是“零个或多个匹配项”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM