如何查找字符串并替换File中的每个匹配项

时间:2014-04-27 14:05:35

标签: c# regex

我在不同的行中有39次包含字符串“CRef”的文件,我需要的是将每个“CRef”更改为“CRef1”,“CRef2”,.....等等。

例如输入:

<CrossReferenceSource Self="CRef" AppliedFormat="uf4">Depressed people are often dependent on others emotionally and seek reassurance in ways that distance others. They may often overvalue relationships.
<CrossReferenceSource Self="CRef" AppliedFormat="uf4" Hidden="false">The cognitive symptoms of depression interfere with work. Three ways in which depression may impair work performance are (1) interpersonal relationships (depressed people are seen as irritable, pessimistic, and withdrawn); (2) productivity  

输出应该是

<CrossReferenceSource Self="CRef1" AppliedFormat="uf4">Depressed people are often dependent on others emotionally and seek reassurance in ways that distance others. They may often overvalue relationships.
<CrossReferenceSource Self="CRef2" AppliedFormat="uf4" Hidden="false">The cognitive symptoms of depression interfere with work. Three ways in which depression may impair work performance are (1) interpersonal relationships (depressed people are seen as irritable, pessimistic, and withdrawn); (2) productivity

我尝试的是MatchCollection所有“CRef”和foreach循环播放每场比赛,但结果是

<CrossReferenceSource Self="CRef12" AppliedFormat="uf4">Depressed people are often dependent on others emotionally and seek reassurance in ways that distance others. They may often overvalue relationships.
<CrossReferenceSource Self="CRef12" AppliedFormat="uf4" Hidden="false">The cognitive symptoms of depression interfere with work. Three ways in which depression may impair work performance are (1) interpersonal relationships (depressed people are seen as irritable, pessimistic, and withdrawn); (2) productivity

等等。

这是我尝试过的示例代码:

int Count = 1;
MatchCollection CRef = Regex.Matches(File, @"CRef");

foreach (var item in CRef)
{
    string cross = Regex.Replace(item.ToString(), @"CRef", "CRef" + Count.ToString());
    Count++;
    final3 = final3.Replace(item.ToString(),cross);    
}

2 个答案:

答案 0 :(得分:1)

查看此问题regex replacement with a increasing number

对于您的具体情况,这样的事情应该有效:

        string test = "<CrossReferenceSource Self=\"CRef\"><CrossReferenceSource Self=\"CRef\">";
        Regex match = new Regex("CRef");
        int count = 0;
        string result = match.Replace(test, delegate(Match t)
        {
            return "CRef" + count++.ToString();
        });

答案 1 :(得分:0)

如果输入文件是XML文件,则应将其作为XML处理,而不是纯文本。

你可以这样做:

var doc = XDocument.Load("file.xml");
var attributes = doc.Root.Descendants("CrossReferenceSource")
                    .Select(e => e.Attribute("Self"))
                    .Where(a => a != null);
int count = 0;
foreach (var a in attributes)
{
    a.Value = "CRef" + (++count);
}
doc.Save("file.xml");