Java tutorial
//package com.java2s; import java.util.regex.Pattern; public class Main { static public String replaceNotExpectedPattern(String text, Pattern pattern, String repl) { if (repl == null || repl.isEmpty()) { repl = ""; } while (!text.isEmpty()) { if (pattern.matcher(text).matches()) { return text; } // replace last position text = text.substring(0, text.length() - 1) + repl; } return text; } static public String replaceNotExpectedPattern(String text, Pattern pattern) { return replaceNotExpectedPattern(text, pattern, null); } }