简体   繁体   中英

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.

But if you must use regex you need to enable the Singleline option so that the dot character (.) matches newline characters as well eg

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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