2013-04-23 201 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