2013-04-23 204 views
2

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

这是我的输入字符串。正则表达式应该匹配以<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> 
+9

正则表达式往往是用于解析XML一个糟糕的选择。我建议使用像“XDocument”这样的XML解析器。 – Oded 2013-04-23 19:05:16

+2

你的'Regex.Replace'函数是什么样的?当你跑他们时发生了什么? – 2013-04-23 19:07:59

+0

我明白了,但我们需要去除基于正则表达式格式提供的运行时配置信息。 – apdev 2013-04-23 19:08:21

回答

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); 
} 
+0

感谢它的工作! – apdev 2013-04-24 16:51:32

+0

乐意提供帮助,但请从其他答案中得到一些建议 - 选择比正则表达式更好的方法可能会更好。 – Pako 2013-04-24 17:10:03

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>" 
+0

感谢这RegEx工作以及! – apdev 2013-04-24 16:57:19

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