Reputation: 125
I want to replace string matching specific pattern using C# regular expression. I did try out various regular expression with Regex.Replace Function but none of them worked for me. Can anyone help me build correct regex to replace part of string.
Here is my input string. Regex should match string that starts with <message Severity="Error">Password will expire in 30 days
then any characters (even new lines characters) till it finds closing </message>
tag. If regex finds matching pattern then it should replace it with empty string.
Input String :
<message Severity="Error">Password will expire in 30 days.
Please update password using following instruction.
1. login to abc
2. change password.
</message>
Upvotes: 2
Views: 5306
Reputation: 32797
You can use LINQ2XML
but if you want regex
<message Severity="Error">Password will expire in 30 days.*?</message>(?s)
OR
In 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
Upvotes: 4
Reputation: 3379
Like said in comments - XML
parsing may be better suited. Also - this might not be the best solution, depending on what you're trying to achieve. but here's passing unit test - you should be able to make sens of it.
[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);
}
Upvotes: 2
Reputation: 2112
I know there are objections to the approach, but this works for me. (I suspect you were probably missing the RegexOptions.SingleLine, which will allow the dot to match newlines.)
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>"
Upvotes: 2