簡體   English   中英

用C#正則表達式替換字符串模式

[英]Replacing String Pattern with C# Regular Expression

我想用C#正則表達式替換字符串匹配特定模式。 我確實用Regex.Replace函數嘗試了各種正則表達式,但它們都沒有為我工作。 誰能幫我構建正確的正則表達式來替換部分字符串。

這是我的輸入字符串。 正則表達式應匹配以<message Severity="Error">Password will expire in 30 days開頭的字符串<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>

你可以使用LINQ2XML但如果你想要regex

<message Severity="Error">Password will expire in 30 days.*?</message>(?s)

要么

在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

我知道這種方法存在異議,但這對我有用。 (我懷疑你可能錯過了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>"

就像在評論中所說的那樣 - 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM