C# 去除h2标签之间的内容,包括h2标签
我试图使用C#中的正则表达式从字符串中的h2标记之间剥离内容:C# 去除h2标签之间的内容,包括h2标签,c#,html,regex,C#,Html,Regex,我试图使用C#中的正则表达式从字符串中的h2标记之间剥离内容: 内容需要删除其他内容。。。 我有以下Regex,根据我用来测试它的Regex buddy软件,它应该可以工作,但不能: myString = Regex.Replace(myString, @"<h[0-9]>.*</h[0-9]>", String.Empty); myString=Regex.Replace(myString,@“*”,String.Empty); 我有另一个正则表达式,在这之后运行
内容需要删除其他内容。。。
我有以下Regex,根据我用来测试它的Regex buddy软件,它应该可以工作,但不能:
myString = Regex.Replace(myString, @"<h[0-9]>.*</h[0-9]>", String.Empty);
myString=Regex.Replace(myString,@“*”,String.Empty);
我有另一个正则表达式,在这之后运行,以删除所有其他HTML标记,它以相同的方式调用,工作正常。有人能帮我解释一下为什么这不起作用吗?这对我来说很好:
string myString = "<h2>content needs removing</h2> other content...";
Console.WriteLine(myString);
myString = Regex.Replace(myString, "<h[0-9]>.*</h[0-9]>", string.Empty);
Console.WriteLine(myString);
但是请注意,这不会修复嵌套的
标记。正如@fardjad所说,使用正则表达式表示HTML通常不是一个好主意。这对我来说很好:
string myString = "<h2>content needs removing</h2> other content...";
Console.WriteLine(myString);
myString = Regex.Replace(myString, "<h[0-9]>.*</h[0-9]>", string.Empty);
Console.WriteLine(myString);
但是请注意,这不会修复嵌套的
标记。正如@fardjad所说,在HTML中使用正则表达式通常不是一个好主意。不要使用正则表达式
HTML
不是常规语言,因此无法使用正则表达式正确解析
例如,您的正则表达式将匹配:
<h2>sample</h1>
示例
这是无效的。在处理嵌套结构时,这将导致意外的结果(*
是贪婪的,并且匹配所有内容,直到输入HTML字符串中的最后一个结束标记h[0-9]
为止)
您可以使用
XMLDocument
(HTML不是XML,但这对于您要做的事情来说已经足够了),也可以使用。不要使用正则表达式
HTML
不是常规语言,因此无法使用正则表达式正确解析
例如,您的正则表达式将匹配:
<h2>sample</h1>
示例
这是无效的。在处理嵌套结构时,这将导致意外的结果(*
是贪婪的,并且匹配所有内容,直到输入HTML字符串中的最后一个结束标记h[0-9]
为止)
您可以使用XMLDocument
(HTML不是XML,但对于您尝试执行的操作来说已经足够了),也可以使用。尝试以下代码:
String sourcestring = "<h2>content needs removing</h2> other content...";
String matchpattern = @"\s?<h[0-9]>[^<]+</h[0-9]>\s?";
String replacementpattern = @"";
MessageBox.Show(Regex.Replace(sourcestring,matchpattern,replacementpattern));
String sourcestring=“内容需要删除其他内容…”;
字符串匹配模式=@“\s?[^请尝试以下代码:
String sourcestring = "<h2>content needs removing</h2> other content...";
String matchpattern = @"\s?<h[0-9]>[^<]+</h[0-9]>\s?";
String replacementpattern = @"";
MessageBox.Show(Regex.Replace(sourcestring,matchpattern,replacementpattern));
String sourcestring=“内容需要删除其他内容…”;
字符串匹配模式=@“\s?[^有趣。一定有其他原因导致此不起作用。它在自定义CMS的控件内,因此可能没有以正确的格式传递。我会继续挖掘:)有趣。一定有其他原因导致此不起作用。它在自定义CMS的控件内,所以我可能它没有以正确的格式传递。我会继续挖掘:)如果HTML格式正确,XMLDocument或XDocument将起作用,如果HTML格式正确,XDocument将起作用
<h2>sample</h1>
String sourcestring = "<h2>content needs removing</h2> other content...";
String matchpattern = @"\s?<h[0-9]>[^<]+</h[0-9]>\s?";
String replacementpattern = @"";
MessageBox.Show(Regex.Replace(sourcestring,matchpattern,replacementpattern));