import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?x) # invoke extended (aka free-spacing) mode\n"
+ "^ # match beginning of the string\n"
+ "[^\"\\n]* # match zero or more chars other than line terminators and double-quotes\n"
+ "\" # match a double-quote\n"
+ "[^\"\\n]* # match zero or more chars other than line terminators and double-quotes\n"
+ "(?<! # begin a negative lookbehind\n"
+ " \\ # match a space\n"
+ " | # or\n"
+ " \\\\n # match a backslash followed by n\n"
+ ") # end negative lookbehind\n"
+ "\" # match a double-quote\n"
+ "\\n # match a newline\n"
+ "\\ * # match zero or more spaces\n"
+ "\" # match double-quote\n"
+ "[^ \"\\n] # match a character other than a space, double-quote or newline\n"
+ "[^\"\\n]* # match zero or more chars other than line terminators and double-quotes\n"
+ "\" # match a double-quote\n"
+ "\\n? # optionally match a newline\n"
+ "$ # match end of string";
final String string = "a c\"d1 %\"\n"
+ " \"&g i\"\n\n"
+ "\"9\"\n"
+ "\"&\"\n\n"
+ "d a\"fe \"\n"
+ " \"3h j\"\n\n"
+ "a c\"d1 \\n\"\n"
+ " \"&g i\"\n\n"
+ "a\"de f%x\"\n"
+ " \" &12 \"\n\n"
+ "#3 does not match due to space preceding second double-quote\n"
+ "#4 does not match due to a backslash followed by n preceding second double-quote\n"
+ "#5 does not match due to backslash followed by n following third double-quote\n"
+ "#5 does not match due to space following third double-quote\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html