Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove comments between quotes in String

Tags:

java

string

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?)

like image 708
Fortega Avatar asked Jun 18 '26 15:06

Fortega


2 Answers

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.

like image 95
Maroun Avatar answered Jun 21 '26 06:06

Maroun


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

like image 36
Nick Avatar answered Jun 21 '26 05:06

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!