1

我需要使用 RegEx 替换 C# 中的一些文本:

string strSText = "<P>Bulleted list</P><UL><P><LI>Bullet 1</LI><P></P><P>
<LI>Bullet 2</LI><P></P><P><LI>Bullet 3</LI><P></UL>"

基本上我需要摆脱

"<P>"

标签之间引入

"<UL><P><LI>", 
"</LI><P></P><P><LI>" and
"</LI><P></UL>"

执行删除时,我还需要忽略这些标签之间的任何空格。

所以

"</LI><P></P><P><LI>", "</LI>    <P></P><P><LI>", "</LI><P></P><P>   <LI>" or 
"</LI> <P> </P> <P> <LI>"

必须全部替换为

"</LI><LI>"

为此,我尝试使用以下 RegEx 匹配:

strSText = Regex.Replace(strSText, "<UL>.*<LI>", "<UL><LI>", RegexOptions.IgnoreCase);
strSText = Regex.Replace(strSText, "</LI>.*<LI>", "</LI><LI>", 
RegexOptions.IgnoreCase);
strSText = Regex.Replace(strSText, "</LI>.*</UL>", "</LI></UL>", 
RegexOptions.IgnoreCase);

但它执行“贪婪”匹配并导致:

"<P>Bulleted list</P><UL><LI>Bullet 3</LI></UL>"

然后我尝试使用“惰性”匹配:

strSText = Regex.Replace(strSText, "<UL>.*?<LI>", "<UL><LI>", RegexOptions.IgnoreCase);
strSText = Regex.Replace(strSText, "</LI>.*?<LI>", "</LI><LI>", 
RegexOptions.IgnoreCase);
strSText = Regex.Replace(strSText, "</LI>.*?</UL>", "</LI></UL>", 
RegexOptions.IgnoreCase);

这导致:

"<P>Bulleted list</P><UL><LI>Bullet 1</LI></UL>"

但我想要以下结果,它保留所有其他数据:

"<P>Bulleted list</P><UL><LI>Bullet 1</LI><LI>Bullet 2</LI><LI>Bullet 3</LI></UL>"
4

2 回答 2

1

以下正则表达式匹配一个或多个<P>or</P>标签:

(?:</?P>\s*)+

所以如果你把它放在你拥有的其他标签之间,你可以摆脱它们,即

strSText = Regex.Replace(strSText, @"<UL>\s*(?:</?P>\s*)+<LI>", "<UL><LI>", RegexOptions.IgnoreCase);
strSText = Regex.Replace(strSText, @"</LI>\s*(?:</?P>\s*)+<LI>", "</LI><LI>", RegexOptions.IgnoreCase);
strSText = Regex.Replace(strSText, @"</LI>\s*(?:</?P>\s*)+</UL>", "</LI></UL>", RegexOptions.IgnoreCase);
于 2013-09-11T08:15:36.543 回答
1

不是您问题的真正答案,而是对 Jonathon 的更多评论: Parse HTML with HTMLAgilityPack

于 2013-09-11T08:58:43.240 回答