用C#正则表达式替换字符串模式
我想用C#正则表达式替换匹配特定模式的字符串。我确实用Regex.Replace函数尝试了各种正则表达式,但没有一种对我有效。有人能帮我建立正确的正则表达式来替换字符串的一部分吗 这是我的输入字符串。正则表达式应该匹配以用C#正则表达式替换字符串模式,c#,regex,C#,Regex,我想用C#正则表达式替换匹配特定模式的字符串。我确实用Regex.Replace函数尝试了各种正则表达式,但没有一种对我有效。有人能帮我建立正确的正则表达式来替换字符串的一部分吗 这是我的输入字符串。正则表达式应该匹配以密码开头的字符串,该字符串将在30天后过期,然后是任何字符(甚至是新行字符),直到找到关闭标记为止。若正则表达式找到匹配的模式,那个么它应该用空字符串替换它 输入字符串: <message Severity="Error">Password will expire i
密码开头的字符串,该字符串将在30天后过期,然后是任何字符(甚至是新行字符),直到找到关闭
标记为止。若正则表达式找到匹配的模式,那个么它应该用空字符串替换它
输入字符串:
<message Severity="Error">Password will expire in 30 days.
Please update password using following instruction.
1. login to abc
2. change password.
</message>
密码将在30天后过期。
请按照以下说明更新密码。
1.登录abc
2.更改密码。
我知道有人反对这种方法,但这对我来说是可行的。(我怀疑您可能丢失了RegexOptions.SingleLine,它将允许点匹配换行符。)
string input=“lorem ipsum dolor sit ametPassword将在30天后过期。\n请使用以下说明更新密码。\n”
+“1.登录abc\n\n2.更改密码。\n删除ipsum dolor或填写另一条消息”;
字符串模式=@“密码将在30天后过期。*?”;
字符串结果=Regex.Replace(输入,模式,“,RegexOptions.Singleline | RegexOptions.IgnoreCase);
//结果=“lorem ipsum dolor sit Ametlore ipsum dolor sit amet另一条消息”
如评论中所述-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);
}
[TestMethod]
公共void TestMethod1()
{
string input=“密码将在30天后过期。\n”
+“请使用以下说明更新密码。\n”
+“1.登录到abc\n”
+“2.更改密码。\n”
+"";
输入=“其他东西”+输入+“其他东西”;
Regex r=new Regex(“密码将在30天内到期\\..*?”,RegexOptions.Singleline);
input=r.Replace(输入,string.Empty);
aresequal(“其他东西”,输入);
}
您可以使用LINQ2XML
,但如果需要regex
<message Severity="Error">Password will expire in 30 days.*?</message>(?s)
正则表达式在解析XML时往往是一个糟糕的选择。我建议改用像XDocument
这样的XML解析器。您的Regex.Replace
函数是什么样子的?当您运行它们时发生了什么?我理解,但我们需要根据以regex格式提供的运行时配置删除消息。如果您试图忽略特定错误,这是在错误的层。在您已经将XML转换为可用对象之后,在应用程序层执行此操作。看起来您也遇到了一些新的问题,很乐意提供帮助,但请从其他答案中听取一些建议-选择比regex更好的方法可能更好。
<message Severity="Error">Password will expire in 30 days.*?</message>(?s)
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