正则表达式 - 用c#替换文本时删除文本

时间:2013-01-21 14:35:10

标签: c# regex

我正在尝试通过使用它编辑我的一些脚本来学习正则表达式。

我的脚本包含如此

<person name="John">Will be out of town</person><person name="Julie">Will be in town.</person>

我需要替换脚本中的名称值 - 名称的添加总是相同的,但我可能有我不想更新的名称。

我所拥有的简单例子:

string[] names = new string[1];
names[0] = "John-Example";
names[1] = "Paul-Example";

string ToFix = "<person name=\"John\">Will be out of town</person><person name=\"Julie\">Will be in town.</person>"

for (int i=0; i<names.Length; i++)
{
    string Name = names[i];
    ToFix = Regex.Replace(ToFix, "(<.*name=\")(" + Name.Replace("-Example", "") + ".*)(\".*>)", "$1" + Name + "$3", RegexOptions.IgnoreCase);
}

这在很大程度上起作用,但我有两个问题。有时它会删除太多,如果我在字符串中有多个人,它将删除第一个人和最后一个人之间的所有内容,如下所示:

Hello <person name="John">This is John</person><person name="Paul">This is Paul</person>

变为

Hello <person name="John-Example">This is Paul</person>

另外,我想删除名称值后面和结束carrat之前的任何额外文本,以便:

<person name="John" hello>

应更正为:

<person name="John-Example">

我已经阅读了几篇关于正则表达式的文章,并且觉得我在这里缺少一些小东西。我将如何以及为何解决这个问题?

编辑:我认为我使用的这些脚本不能归类为XML - 整个脚本可能有也可能没有&lt;&gt;标签。回到这个问题的原始目标,有人可以解释正则表达式的行为吗?如何在结束标记之前的名称值之后删除额外的文本?

1 个答案:

答案 0 :(得分:2)

你的正则表达式太贪心了。请尝试.*?,而不仅仅是.*

另外,请不要使用正则表达式来解析XML。


以下是使用XDocument

如何做我认为您想要的事情的示例
var xdoc = XDocument.Parse(ToFix);
foreach (var person in xdoc.Elements("person"))
{
    var name = person.Attribute("name");
    if (person.LastAttribute != name)
    {
        person.RemoveAttributes();
        person.SetAttributeValue(name.Name, name.Value + "-Example");
    }
}
var output = xdoc.ToString();