public static String patternLowerCase(String pattern, String string) { if (string == null){ return null; } Matcher m = Pattern.compile(pattern).matcher(string); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, m.group().toLowerCase()); } m.appendTail(sb); return sb.toString(); } public static String patternUpperCase(String pattern, String string) { if (string == null){ return null; } Matcher m = Pattern.compile(pattern).matcher(string); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, m.group().toUpperCase()); } m.appendTail(sb); return sb.toString(); }
Example of use:
//Here's an example of how you use regex to find and capitalize words of length at least 3 in a sentence String text = "example of how you use"; String pattern = "\b\w{3,}\b"; String res = patternUpperCase(pattern, text); System.out.println(res); // prints "EXAMPLE of HOW YOU USE"