【发布时间】:2015-08-12 15:44:35
【问题描述】:
我对正则表达式没有太多经验,并且有一个问题,我需要用&lt; 和&gt; 替换所有> 和< 实例,但要保留HTML 标记。
例如:
String string =" <p class=\"anotherClass\"> Here is some text the value is for H<sub>2</sub>O is > 1 and < 100 <p>";
//need to be converted to:
<p class=\"anotherClass\"> Here is some text the value is for H<sub>2</sub>O is > 1 and < 100 <p>";
我尝试了一些外观和前后表达式,但我似乎无法让它们中的任何一个起作用。例如:
String string =" <p class=\"anotherClass\"> Here is some text the value is for H<sub>2</sub>) is > 1 and < 100 <p>";
String reg1="<(?=[^>\\/]*<\\/)";
Pattern p1 = Pattern.compile(reg1);
test = p1.matcher(string).replaceAll("<");
似乎没有任何作用。
我想知道以前是否有其他人遇到过这种情况,或者是否有人可以给我任何指导?
【问题讨论】:
-
Don't even try。使用 HTML 解析器,它将找出那些
>和<字符在哪里(尽可能),然后让它序列化结果。请注意,它是完全有效的,例如,写成<div >foo</div >。 -
我必须同意。您将无法使用正则表达式处理。
-
是的,使用解析器。 You have a lot of choices. (其实现在想来,这是格式错误的HTML。符号应该已经被转义了。你基本卡住了,你可能不得不求助于通用的XML解析器,然后整理标签这不是真正的标签。)