import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?x) # Free-Spacing\n"
+ "(?(DEFINE) # Define a few subroutines\n"
+ " (?<double>“(?:(?!&[lr]squo;).)*”) # full set of doubles (no quotes inside)\n"
+ " (?<single>‘(?:(?!&[lr]dquo;).)*’) # full set of singles (no quotes inside)\n"
+ " (?<notquotes>(?:(?!&[lr][sd]quo;).)*) # chars that are not quotes\n"
+ ") # end DEFINE\n\n"
+ "^ # Start of string\n"
+ "( # Start group: balanced portion\n"
+ "(?: # Start non-capture group\n"
+ " (?¬quotes) # Any non-quote chars\n"
+ " &l(?<type>[sd])quo; # Opening quote, capture single or double type\n"
+ " # any full singles, doubles, not quotes or recursion\n"
+ " (?:(?&single)|(?&double)|(?¬quotes)|(?R))*\n"
+ " &r\\k<type>quo; # Closing quote of the correct type\n"
+ ")*+ # Repeat non-capture group\n"
+ ") # end balanced portion\n"
+ "\\K\n"
+ "(\n"
+ "(?¬quotes)\n"
+ "&r([sd])quo; # unmatched quote\n"
+ ")";
final String string = "“Full Quote” The Left Quote is Missing”\n";
final String subst = "&l\\7quo;\\6";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceFirst(subst);
System.out.println("Substitution result: " + result);
}
}
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