import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?(DEFINE)\n"
+ " (?<palindrome>\n"
+ " # Recursive alternative first to match recursive palindromes.\n"
+ " # Invert alternatives order to match nested palindromes individually\n"
+ " # and (drastically) reduce backtracking.\n"
+ " (?<l1>\\p{L})\\p{M}* [\\s\\p{P}]* (?&palindrome) [\\s\\p{P}]* \\k<l1>\\p{M}*\n"
+ " | (?<l2>\\p{L})\\p{M}* [\\s\\p{P}]* \\k<l2>\\p{M}*\n"
+ " | \\p{L}\\p{M}*\n"
+ " )\n"
+ ")\n\n"
+ "(?<=[\\s\\p{P}]|^) (?&palindrome) (?(?=\\s*\\p{P}) (?:\\s*\\p{P})+ | (?=\\s|$))";
final String string = "~ should not match\n"
+ "jambon\n\n"
+ "~ Simple\n"
+ "a\n"
+ "bb\n"
+ "cc\n"
+ "ddd\n"
+ "bob\n"
+ "ara\n"
+ "abbb a\n"
+ "radar\n"
+ "essayasse\n\n"
+ "~ Spaces, diacritics and punctuation\n"
+ "Don't nod!Step on no pets.\n"
+ "Ésope reste ici et se repose.\n"
+ "Élu par cette crapule ! ?\n"
+ "Tu l'as trop écrasé, César, ce Port-Salut !\n"
+ "Zeus a été à Suez.\n\n"
+ "~ Recursive palindromes\n"
+ "a a !\n"
+ "ah ha !\n"
+ "abba / ab b a\n"
+ "~\n"
+ "abba été àb ba\n"
+ "~\n"
+ "abba, ab b a, abbà été àb ba";
final String subst = "[$0]";
final Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.COMMENTS);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(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