Reputation: 21
I am currently doing comment analysis with some Java code and needed to do the following opperation:
comment = comment.replaceAll("/**", "");
But I am meet with this Exception:
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)
Edit: The exception also occurs when I do
comment = comment.replaceAll("**/", "");
and
comment = comment.replaceAll("*/", "");
Do anyone know why this happens and do anyone have a workaround?
Upvotes: 0
Views: 4098
Reputation: 7705
Two things are wrong with this code:
comment = comment.replaceAll("/**", "");
*
is a special regex character to match any number of any characters, based on the context that you are removing comments you want to match the literal *
so you need your regex to be /\*\*
.\*
as an escape code (like \n
being newline character), but \*
isn't one. It needs to be \\*
instead, meaning the String should be /\\*\\*
This is correct.
comment = comment.replaceAll("/\\*\\*", "");
As an aside, even if \*
was a valid escape code, the thing it got replaced with would be passed into regex, not \*
. (e.g., if you put \n
in the newline character would go into regex, not a backslash and a lowercase n.
You may want to go with something like this though
comment = comment.replaceAll("/\\**\\*/", "");
which would be removing /* <stuff> */
. This catches doc-comments and regular multi-line comments in addition to removing the entire comment. It depends on how you've read the string though.
Upvotes: 0
Reputation: 61
First parameter of "replaceAll" is a regular expression, and character "*" has a special meaning in regular expressions.
You can use something like this:
String a = "/**hola mundo/**, adios mundo";
String output = a.replaceAll("/\\*\\*", "");
System.out.println(output); // --> "hola mundo, adios mundo"
Upvotes: 2
Reputation: 421040
replaceAll
takes a regular expression, and /**
isn't a valid regular expression.
If you just want to remove /**
, use replace
instead.
Upvotes: 6