I need to remove comments from a String. Comments are specified using quotes. For example:
removeComments("1+4 'sum'").equals("1+4 ");
removeComments("this 'is not a comment").equals("this 'is not a comment");
removeComments("1+4 'sum' 'unclosed comment").equals("1+4 'unclosed comment");
I could iterate through the characters of the String, keeping track of the indexes of the quotes, but I would like to know if there is a simpler solution (maybe a regex?)
You can use replaceAll:
str = str.replaceAll("\\'.*?\\'", "");
This will replace the first and the second ' and everything between them with "" (Thus, will remove them).
Edit: As stated on the comments, there is no need to backslash the single quote.
If you don't need to be able to have quotes inside the comment, this will do it:
input.replaceAll("'[^']+'", "");
It matches a quote, at least one of anything that isn't a quote, then a quote.
Working example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With