如何提取并替换具有不同值的子字符串

本文关键字:字符串 替换 何提取 提取 | 更新日期: 2023-09-27 18:32:18

>我有以下字符串:"使用以下数据[环境变量][测试帐户]状态已连接"

我想做的是将[EnvironmentVar][TestAccount]替换为从XML文件中检索的数据。所以我需要首先将 [EnvironmentVar][TestAccount] 提取到它自己的字符串中,然后我已经有了一个查询 XML 的方法,但此外,一旦我检索到值,我需要做的是将其替换为原始字符串。

还有另一个曲线球,结构不会总是:

[EnvironmentVar][TestAccount] 

它可能有额外的"节点",例如:

[SystemTest][EnvironmentVar][TestAccount]

[Region][SystemTest][EnvironmentVar][TestAccount]

只要我能从原始字符串中提取此模式,我就可以从中获取数据。正如我上面提到的,我需要做的是将"[SystemTest][EnvironmentVar][TestAccount]"替换为我检索到的数据。因此,例如,返回的可能是像"UKUser"这样简单的东西,因此新字符串最终将是"使用以下数据UKUser状态已连接"

任何指导将不胜感激,我相信有很多方法可以做到这一点。

更新

这里和例子

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...

如何提取并替换具有不同值的子字符串

如果您

也想替换"额外节点",当它们存在时:

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

您可以分解令牌并单独处理;

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 "";
            }
       });

如果你的模式总是以 [ 开头并以 ] 结尾,你可以只使用子字符串轻松做到这一点。

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);