Joey Weidman Joey Weidman - 2 months ago 11
Java Question

Java Regex: Finding double quotes and noticing escape chracters

I am having trouble making a regex that notices escape characters inside of quotes.

For example, Two "quoted strings" in "this line" would return:


quoted strings

this line


This string "contains an \" escaped quote mark". would return:


contains an \" escaped quote mark


I made a regex to match quotes

\\\"[^\\\"\\n]*\\\"



  • \\" quote

  • [^\\"\n]* anything but a quote or new line

  • \\" quote



How would I make a regex that ignores escape characters inside of the quotes?

Note: I only want the escape characters to be noticed inside of the quotes, so something like This is \"a dog" should still output a dog.

Answer

Try this.

Pattern p = Pattern.compile("\"(?:\\\\\"|[^\"])*\"");
Matcher m = p.matcher("\"contains an \\\" escaped quote mark\"");
while (m.find()) {
    System.out.println(m.group());
}
Comments