在我的应用程序中,我将页面的 HTML 源代码加载到字符串中。在此 HTML 中,我想删除特定 HTML 注释之间的某些内容。
例如:
//the entire String will be HTML source like this, of the entire page
<div id="someid">
<a href="#">Some text</a>
<!-- this_tag_start 123 -->
<p> This text between the tags to be removed </p>
<!-- this_tag_end 123 -->
<a href="#">Some text</a>
</div>
this_tag_start 123
和相应的“end”是由我们的服务器生成的。 123
号码会有所不同。
在我的程序中,我有一个包含整个 HTML 源代码的字符串。我想删除这两个评论标签之间的文本(评论标签是否保留并不重要)。这些 html 注释标记可以在整个 HTML 源代码中出现多次。
现在我正在使用此正则表达式来删除内容:
htmlString = htmlString.replaceAll(
"<!-- this_tag_start(.*?)<!-- this_tag_end[\\s\\d]+-->",""
);
这可以正常工作并正确删除这些注释标签以及开始标签和结束标签之间的内容。然而,感觉这并不是一个优雅的解决方案。应该有更好/更快的方法来做到这一点,对吗?
如果重要的话,字符串是由 WebDriver 的 getPageSource() 方法生成的。
最佳答案
1。优雅
However, it doesn't feel like it's an elegant solution.
以下是原始正则表达式的两个变体:
变体 1
(?s)\s*<!-- this_tag_start([\s\d]+)-->.+?<!-- this_tag_end\1-->\s*
此变体使用 id 的反向引用。我发现的一个缺点是这种变体只允许 id 为空格。只要您控制评论,这就不是问题。
变体 2
(?s)\s*<!-- this_tag_start\s+(\d+)\s*-->.+?<!-- this_tag_end\s+\1\s*-->\s*
此变体再次使用 id 的反向引用。但是,对于 id 的预期方式更加明确:一个或多个空格、一个或多个数字后跟零个或多个空格。
2。速度
There should be a better/faster way to do it, right?
在内部,String#replaceAll
方法调用 Pattern#compile
。模式编译以缓慢而闻名。
我会缓存编译结果以加快替换速度。 操作方法如下:
public class MyCrawler {
// Compile once, run multiple times
private static final Matcher COMMENT_REMOVER = Pattern.compile("the regex here...").matcher("");
public void doCrawl() {
String htmlString = loadHtmlSource();
htmlString = COMMENT_REMOVER.reset(htmlString).replaceAll("");
}
...
}
关于java - 删除大型 Java 字符串的部分(它包含 HTML 源代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31841281/