TextUtils { public static Pattern buildSimilarToPattern(String pattern) { String[] s = SPLITLIKE.split(pattern); StringBuilder b = new StringBuilder(); b.append("^"); if (s.length == 0) { for (int i = 0; i < pattern.length(); i++) { switch (pattern.charAt(i)) { case '%': b.append(".*"); break; case '_': b.append("."); break; default: } } } else { int pos = 0; for (int i = 0; i < s.length; i++) { boolean esc = false; if (s[i].endsWith("\\")) { pos++; if (i + 1 < s.length) { s[i + 1] = s[i].substring(0, s[i].length() - 1) + pattern.charAt(pos + s[i].length() - 1) + s[i + 1]; continue; } else { s[i] = s[i].substring(0, s[i].length() - 1); esc = true; } } if (!s[i].isEmpty()) { String t = ESCAPE.matcher(s[i]).replaceAll("\\\\"); b.append(DOT.matcher(t).replaceAll("\\\\.")); pos += s[i].length(); } if (pos < pattern.length()) { switch (pattern.charAt(pos)) { case '%': if (esc) { b.append("%"); } else { b.append(".*"); } pos++; break; case '_': if (esc) { b.append("_"); } else { b.append("."); } pos++; break; default: } } } while (pos < pattern.length()) { switch (pattern.charAt(pos)) { case '%': b.append(".*"); pos++; break; case '_': b.append("."); pos++; break; default: } } } b.append("$"); return Pattern.compile(b.toString()); } private  TextUtils(); static String getEolStr(); static String stringToHTMLString(String string); static int[] getLocation(int bl, int bc, int el, int ec,
                String[] lines); static Pattern buildLikePattern(String pattern); static Pattern buildLikePattern(String pattern, boolean caseInsensitive); static Pattern buildSimilarToPattern(String pattern);  }
@Test public void testSimilarToPattern() { Pattern p = TextUtils.buildSimilarToPattern("st[ra]_+8"); match(p, "str%aa8"); match(p, "str%ab8"); notMatch(p, "sta8"); }