我有以下字符串:"使用以下数据[EnvironmentVar] [TestAccount]状态已连接"
我想要做的是将[EnvironmentVar] [TestAccount]替换为从XML文件中检索的数据。所以我需要首先将[EnvironmentVar] [TestAccount]提取到自己的字符串中,然后我已经有了一个查询XML的方法,但是一旦我检索到该值,我需要做的就是替换它进入原始字符串。
还有另一个曲线球,结构不一定是:
[EnvironmentVar][TestAccount]
它可能有额外的"节点"像:
[SystemTest][EnvironmentVar][TestAccount]
或
[Region][SystemTest][EnvironmentVar][TestAccount]
只要我可以从原始字符串中提取此模式,我就可以从中获取数据。正如我上面提到的,然后我需要做的就是替换" [SystemTest] [EnvironmentVar] [TestAccount]"我已检索到的数据。例如,它可能就像" UKUser"返回所以新字符串最终会被"使用以下数据连接UKUser状态"
任何指导都将受到赞赏,我确信有很多方法可以做到这一点。
更新
Heres and example
string myQuery = "Using the following data [SystemTest][EnvironmentVar][TestAccount]";
string xmlQuery = RetrieveXMLQuery(myQuery);
//So now I want xmlQuery to be "[SystemTest][EnvironmentVar][TestAccount]"
//XML query now gets executed
string xmlResult = RetrieveXMLValue(xmlQuery);
//xmlResult would now be "UKUser"
//Now what I want to do is take the string "Using the following data [SystemTest][EnvironmentVar][TestAccount]" and replace the nodes with UKUser is it becomes "Using the following data UKUser"
//Remember that the number of nodes and the sequence wont always be the same...
答案 0 :(得分:1)
如果您想要替换“额外节点”,如果它们存在:
string input = "Using the following data [EnvironmentVar][TestAccount] status is connected";
string newData = "UKUser";
string output = Regex.Replace(input, @"(\[.*\])", newData);
Console.WriteLine(output); // Using the following data UKUser status is connected
答案 1 :(得分:0)
你可以分解标记并单独处理;
text = Regex.Replace(text, @"(\[[A-Za-z]+\])", delegate(Match match)
{
switch (match.Groups[1].Value)
{
case "[SystemTest]":
return (string)SomeXml.Element("SystemTestNode");
case "[TestAccount]":
return "123456";
default:
return "";
}
});
答案 2 :(得分:0)
如果您的模式始终以[并以]结尾,则只需使用子字符串即可轻松完成此操作。
string original = "Using the following data [EnvironmentVar][TestAccount] status is connected";
string replacementText = "UKUser";
string newString = original.Substring(0, original.IndexOf("[")) + replacementText + original.Substring(original.LastIndexOf("]")+1);