Search code examples
javaregexreplaceall

Representing carriage returns and quotes with regular expressions in java


I want to replace a carriage return followed by quotation marks with just quotation marks. For example, if I have:

Hello World
"Hello World"

I would like the result to be:

Hello World"Hello World"

This is my attempt, where String text is what I have above:

String adjusted = text.replaceAll("[\n][\"], "\"");

However, my IDE does not accept this. Thanks for the help!


Solution

  • You can use replace instead of replaceAll to avoid matching regular expression, but instead matching literals.

    String adjusted = text.replace("\n\"", "\"");
    

    If you want this method to use you operating system line separators you should use

    String adjusted = text.replace(System.lineSeparator()+"\"", "\"");