Fortega
Fortega

Reputation: 19682

Remove comments between quotes in 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?)

Upvotes: 2

Views: 299

Answers (2)

Maroun
Maroun

Reputation: 95958

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.

Upvotes: 7

Nick H
Nick H

Reputation: 11535

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

Upvotes: 2

Related Questions