有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在<之间删除内容!和/>

我有一个文本文件,它是将HTML解析成纯文本文件的结果。我需要去掉类似于XHTML注释的内容,如下所示:

<!--
if (!document.phpAds_used)
 document.phpAds_used = ',';
 phpAds_random = new String
 (Math.random()); phpAds_random =
 phpAds_random.substring(2,11);
 document.write ("<" + "script
 language='JavaScript'
 type='text/javascript' src='");
 document.write
 ("http://www.writers.net/Openads/adjs.php?n="
 + phpAds_random); document.write ("&what=zone:5&target=_blank");
 document.write ("&exclude=" +
 document.phpAds_used); if
 (document.referrer) document.write
 ("&referer=" +
 escape(document.referrer));
 document.write ("'><" + "/script>");
 // -->

如何使用Java摆脱<!--//-->之间的任何东西


共 (1) 个答案

  1. # 1 楼答案

    一个简单的解决方案是使用String.replaceAll()方法

    例如,类似以下代码的代码应该可以工作:

    String x = "wow <!  //  > zip, here's <!  comment here // > another one";
    x = x.replaceAll("<! .*?//\\s* >", "");
    System.out.println(x);  // prints out "wow  zip, here's  another one"
    

    \\s*不匹配任何空格或多个空格,因为示例中有空格,但说明中没有。.*?使其成为非贪婪匹配,因此它将匹配到第一个// >

    如果反复运行,可以使用Pattern,只需为正在处理的每个块重新生成匹配器:

    Pattern.compile("<! .*?//\\s* >").matcher(x).replaceAll("")