Programming Tips - Java: Do a String replace with a compiled Pattern

Date: 2012mar8 Update: 2025sep19 Language: Java Q. Java: Do a String replace with a compiled Pattern A. Use Matcher.replaceFirst() has shown in this full example:
import java.util.regex.Pattern; import java.util.regex.Matcher; class Demo { static String compiledPatternReplace(Pattern pat, String in, String changeTo) { Matcher matcher = pat.matcher(in); return matcher.replaceFirst(changeTo); } public static void main(String []args) { // This Pattern will match any word starting with "p" Pattern pat = Pattern.compile("p\\w+", Pattern.CASE_INSENSITIVE); String out = compiledPatternReplace(pat, "hello people", "animals"); System.out.println("out=" + out); } }
Output:
out = "hello animals";
You can use String's replaceFirst() or replaceAll() if don't want to compile the pattern.