如何替换字符串查询中的多个值
问题描述:
注意:我已经写了一段代码,用[]括号替换了这些值.
问题:HSA:3269被替换为value1,但是[]中的其余值未被替换为value2,value3.
Note:I have written the piece of code for replacing the values with in the [] brackets.
Issue: HSA:3269is getting replaced with value1,but rest of the values inside [] not getting replaced with value2,value3.
using System.Linq;
using System.Xml.Linq;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var pattern = @"\[(.*?)\]";
var query = "H1-receptor antagonist [HSA:3269] heelo [PATH:hsa04080(3269)] world [xyz]";
var matches = Regex.Matches(query, pattern);
string ReplaceableValue = query;
string[] array = { "value1", "value2", "value3" };
foreach (Match m in matches)
{
System.Console.WriteLine(m.Groups[1]);
for (int i = 0; i <= m.Length; i++)
{
ReplaceableValue = ReplaceableValue.Replace(m.Value.ToString(), array[i]);
}
}
System.Console.WriteLine(ReplaceableValue);
System.Console.ReadLine();
}
}
}
答
您已经有了解决方案.只需将Group
替换为Value
.希望对您有帮助.
You already have the solution. Just replace theGroup
with yourValue
. Hope it will help you.
int i=0;
foreach (Match m in matches)
{
System.Console.WriteLine(m.Groups[1]);
//for (int i = 0; i <= m.Length; i++)
{
//ReplaceableValue = ReplaceableValue.Replace(m.Value.ToString(), array[i]);
ReplaceableValue = ReplaceableValue.Replace(m.Groups[1].ToString(), array[i++]);
}
}
System.Console.WriteLine(ReplaceableValue);