用C#正则表达式替换字符串模式

时间:2013-04-23 19:03:29

标签: c# regex

我想用C#正则表达式替换字符串匹配特定模式。我确实用Regex.Replace函数尝试了各种正则表达式,但它们都没有为我工作。任何人都可以帮我构建正确的正则表达式来替换部分字符串。

这是我的输入字符串。正则表达式应匹配以<message Severity="Error">Password will expire in 30 days开头的字符串,然后匹配任何字符(甚至换行符号),直到找到结束</message>标记。如果正则表达式找到匹配的模式,那么它应该用空字符串替换它。

输入字符串:

<message Severity="Error">Password will expire in 30 days.
Please update password using following instruction.
1. login to abc
2. change password.
</message>

3 个答案:

答案 0 :(得分:4)

如果您需要LINQ2XML

,可以使用regex
<message Severity="Error">Password will expire in 30 days.*?</message>(?s)

OR

在linq2Xml

XElement doc=XElement.Load("yourXml.xml");

foreach(var elm in doc.Descendants("message"))
{
    if(elm.Attribute("Severity").Value=="Error")
        if(elm.Value.StartsWith("Password will expire in 30 days"))
        {
            elm.Remove();
        }
}
doc.Save("yourXml");\\don't forget to save :P

答案 1 :(得分:2)

我知道这种做法存在异议,但这对我有用。 (我怀疑你可能错过了RegexOptions.SingleLine,这将允许点匹配换行符。)

string input = "lorem ipsum dolor sit amet<message Severity=\"Error\">Password will    expire in 30 days.\nPlease update password using following instruction.\n"
        + "1. login to abc\n\n2. change password.\n</message>lorem ipsum dolor sit amet <message>another message</message>";

string pattern = @"<message Severity=""Error"">Password will expire in 30 days.*?</message>";

string result = Regex.Replace(input, pattern, "", RegexOptions.Singleline | RegexOptions.IgnoreCase);

//result = "lorem ipsum dolor sit ametlorem ipsum dolor sit amet <message>another message</message>"

答案 2 :(得分:2)

如评论中所述 - XML解析可能更适合。此外 - 这可能不是最佳解决方案,具体取决于您要实现的目标。但是这里通过单元测试 - 你应该能够理解它。

[TestMethod]
public void TestMethod1()
{
    string input = "<message Severity=\"Error\">Password will expire in 30 days.\n"
                    +"Please update password using following instruction.\n"
                    +"1. login to abc\n"
                    +"2. change password.\n"
                    +"</message>";
    input = "something other" + input + "something else";

    Regex r = new Regex("<message Severity=\"Error\">Password will expire in 30 days\\..*?</message>", RegexOptions.Singleline);
    input = r.Replace(input, string.Empty);

    Assert.AreEqual<string>("something othersomething else", input);
}
相关问题