Java replaceAll - 替换" / **"用""

时间:2015-05-12 13:47:37

标签: java replaceall

我目前正在使用一些Java代码进行评论分析,需要执行以下操作:

comment = comment.replaceAll("/**", "");

但我遇到了这个例外:

    Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 2
/**
  ^
    at java.util.regex.Pattern.error(Unknown Source)
    at java.util.regex.Pattern.sequence(Unknown Source)
    at java.util.regex.Pattern.expr(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.util.regex.Pattern.<init>(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.lang.String.replaceAll(Unknown Source)
    at commentCoupler.coupler.commentCriteriaForfilled(coupler.java:234)
    at commentCoupler.coupler.analyze(coupler.java:64)
    at commentCoupler.coupler.recursiveCoupler(coupler.java:27)
    at commentCoupler.coupler.recursiveCoupler(coupler.java:22)
    at commentCoupler.coupler.recursiveCoupler(coupler.java:22)
    at commentCoupler.main.main(main.java:16)

编辑:当我这样做时也会发生异常

comment = comment.replaceAll("**/", "");

comment = comment.replaceAll("*/", "");

有谁知道为什么会发生这种情况,有没有人有解决方法?

4 个答案:

答案 0 :(得分:6)

replaceAll采用正则表达式,/**不是有效的正则表达式。

如果您只想删除/**,请改用replace

答案 1 :(得分:2)

“replaceAll”的第一个参数是正则表达式,而字符“*”在正则表达式中具有特殊含义。

您可以使用以下内容:

String a = "/**hola mundo/**, adios mundo";
String output = a.replaceAll("/\\*\\*", "");
System.out.println(output); // --> "hola mundo, adios mundo"

答案 2 :(得分:0)

comment = comment.replaceAll("/\**", "");

答案 3 :(得分:0)

此代码有两个问题:

comment = comment.replaceAll("/**", "");
  1. *是一个特殊的正则表达式字符,用于匹配任意数量的任何字符,具体取决于您要删除要与文字*匹配的评论的上下文,因此您需要正则表达式为{{ 1}}。
  2. 因为这个正则表达式在java字符串中,所以它会尝试将/\*\*作为转义码读取(如\*为换行符),但\n不是一个。它必须是\*,这意味着字符串应该是\\*
  3. 这是正确的。

    /\\*\\*

    顺便说一句,即使comment = comment.replaceAll("/\\*\\*", ""); 是有效的转义码,它所取代的东西也会被传递到正则表达式,而不是\*。 (例如,如果你将\*放在换行符中,则会进入正则表达式,而不是反斜杠和小写n。

    你可能想要使用类似的东西

    \n

    将删除comment = comment.replaceAll("/\\**\\*/", ""); 。除了删除整个注释之外,这还会捕获doc-comments 常规多行注释。这取决于你如何读取字符串。

相关问题