我的程序解析一个包含路径的XML文件。现在,我需要解析特殊的文件夹,例如Appdata
在不同的Windows设备上:
<entry path="C:\Users\Simon\AppData\Roaming\myprogram" />
我的尝试是将行更改为:
<entry path="#{APPDATA}\myprogram" />
并使用正则表达式进行解析:
string pattern = "#{ * }"; // what does fit here?
我已经阅读过一些正则表达式的教程,但我无法弄清楚哪种正则表达式适合这里。
如何在正则表达式之间#{
以及}
使用正则表达式获取内容?
只需注册要替换的通用占位符即可,例如
Dictionary<string, string> placeholders = new Dictionary<string, string>
{
{ "#{APPDATA}", @"C:\Users\Simon\AppData\Roaming" },
{ "#{SYSTEM32}", @"C:\Windows\System32" }
};
string ReplacePlaceholders (string text)
{
foreach (var kv in placeholders)
{
text = text.Replace(kv.Key, kv.Value);
}
return text;
}
像这样使用:
// this would come from the XML attribute
string path = @"#{APPDATA}\myprogram";
string newPath = ReplacePlaceholders(path);
Console.WriteLine(newPath); // C:\Users\Simon\AppData\Roaming\myprogram
至于实际值路径,还可以Environment.GetFolderPath
与Environment.SpecialFolder
枚举一起使用以获取实际路径。但是对于替代品和其他值,答案仍然适用
最后,由于我不确定您是从哪个方向进行这些替换,因此您当然也可以在上述字典中反转映射。我只是假设您有要用实际路径替换的占位符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句