净正则表达式匹配分组和重复的问题 [英] .Net Regex match grouping and repetition question
问题描述
我有在ASP.Net应用以下VB.Net 2.0:
输出= Regex.Replace(输出, "<p>(?:(?:\<\!\-\-.*?\-\-\>)|&(?:nbsp|\#0*160|x0*A0);|<br\s*/?>|[\s\u00A0]+)*</p>",的String.Empty,RegexOptions.Compiled或者RegexOptions.CultureInvariant或者RegexOptions.IgnoreCase或者RegexOptions.Singleline)
例东西,它匹配得好:
-
&LT; P&GT;&LT; / P&GT;
-
&LT; P&GT; &LT; / P&GT;
-
&LT; P&GT;&LT; BR /&GT;&LT; BR /&GT;&LT; / P&GT;
-
&LT; P&GT;&LT;! - 评论 - &GT;&LT;! - 评论 - &GT;&LT; / P&GT;
-
&LT; P&GT;&安培; NBSP;&安培; NBSP;&LT; / P&GT;
-
&LT; P&GT;&LT; BR /&GT;&安培; NBSP;&LT; / P&GT;
-
&LT; P&GT;&LT;! - 评论 - &GT;&LT; BR /&GT;&LT;! - 评论 - &GT;&LT; / P&GT;
-
&LT; P&GT;&安培; NBSP;&LT; BR /&GT;&LT; / P&GT;
东西的例子,我想匹配,但它不会:
-
&LT; P&GT; &LT;! - [如果supportLineBreakNewLine!] - &GT;&LT; BR /&GT; &LT;! - [ENDIF] - &GT;&LT; / P&GT;
如何让我的组和重复工作,我多么希望他们?
编辑:哎呀,忘了注释组。 修改#2:哎呀,忘了失败。 修改#3:固定的例子。 修改#4:基于答案更新的正则表达式
结论:
下面是我的基准测试结果所有的三个答案。由于三个匹配现在的一切,我跑了每一个到10,000迭代文本块:
矿:
<p\s*>(?:(?:<!--.*?-->)|&(?:nbsp|\#0*160|x0*A0);|<br\s*/?>|[\s\u00A0]+)*</p>
6.312
浓汤:
<p\s*>(?:[\s\u00A0]+|&(?:nbsp|\#0*160|x0*A0);|<br\s*/?>|<!--(?:[^-]+|-(?!-))*-->)*</p>
6.05
steamer25:
<p\s*>(?:(?:\ \;)|(?:\&\#0*160\;)|(?:<br\s*/?>)|\s|\u00A0|<!\-\-[^(?:\-\-)]*\-\->)*</p>
6.121
浓汤的是最快的,所以我会纪念他为正确答案。
试试这个普通的前pression:
<$p$p><$c$c><p\s*>(?:[\s\u00A0]+|&(?:nbsp|\#0*160|x0*A0);|<br\s*/?>|<!--(?:[^-]+|-(?!-))*-->)*</p>I have the following VB.Net 2.0 in an ASP.Net app:
output = Regex.Replace(output, "<p>(?:(?:\<\!\-\-.*?\-\-\>)|&(?:nbsp|\#0*160|x0*A0);|<br\s*/?>|[\s\u00A0]+)*</p>", String.Empty, RegexOptions.Compiled Or RegexOptions.CultureInvariant Or RegexOptions.IgnoreCase Or RegexOptions.Singleline)
Example stuff it matches well:
<p></p>
<p> </p>
<p><br/><br/></p>
<p><!-- comment --><!-- comment --></p>
<p> </p>
<p><br/> </p>
<p><!-- comment --><br/><!-- comment --></p>
<p> <br/></p>
Examples of stuff I'd like to match but it doesn't:
<p > <!--[if !supportLineBreakNewLine]--><br /> <!--[endif]--></p>
How do I make the groups and repetitions work how I want them to?
Edit: oops, forgot the comment group. Edit #2: oops, forgot a fail. Edit #3: fixed examples. Edit #4: updated regex based on answers
Conclusion:
Here are my benchmarked results for all three answers. Since all three now match everything I ran each one through 10,000 iterations on a block of text:
Mine:
<p\s*>(?:(?:<!--.*?-->)|&(?:nbsp|\#0*160|x0*A0);|<br\s*/?>|[\s\u00A0]+)*</p>
6.312
Gumbo:
<p\s*>(?:[\s\u00A0]+|&(?:nbsp|\#0*160|x0*A0);|<br\s*/?>|<!--(?:[^-]+|-(?!-))*-->)*</p>
6.05
steamer25:
<p\s*>(?:(?:\ \;)|(?:\&\#0*160\;)|(?:<br\s*/?>)|\s|\u00A0|<!\-\-[^(?:\-\-)]*\-\->)*</p>
6.121
Gumbo's was the fastest, so I'll mark his as the correct answer.
Try this regular expression:
<p\s*>(?:[\s\u00A0]+|&(?:nbsp|\#0*160|x0*A0);|<br\s*/?>|<!--(?:[^-]+|-(?!-))*-->)*</p>
这篇关于净正则表达式匹配分组和重复的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!