如何查找字符串并替换文件中的每个匹配项
本文关键字:文件 替换 串并 何查找 查找 字符串 字符 | 更新日期: 2023-09-27 18:00:19
我在不同的行中有39次包含字符串"CRef"的文件,我需要的是将每个"CRref"更改为"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
我尝试的是在每次比赛中为所有"CRef"和foreach
循环使用MatchCollection
,但结果是
<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);
}
看看这个问题,用越来越多的替换正则表达式
对于您的具体情况,应该使用类似的方法:
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();
});
如果输入文件是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");