0

Which way is more efficient to replace characters/substring in a string. I have searched and i have found two ways :

output = output.replaceAll(REGEX, REPLACEMENT);

or

Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(output);
output = m.replaceAll(REPLACEMENT);

I mean with efficiency : less time, loops and/or new variables.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Abid
  • 91
  • 1
  • 8
  • See [java.util.regex - importance of Pattern.compile()?](http://stackoverflow.com/questions/1720191/java-util-regex-importance-of-pattern-compile) – Wiktor Stribiżew Mar 21 '17 at 12:16

1 Answers1

4

If you look at the String method replaceAll it does the same under the hood:

public String replaceAll(String regex, String replacement) {
    return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}

If you want to use the same pattern multiple times. It's better to go with the second option as you will not need to recompile it every time.

Justas
  • 811
  • 1
  • 11
  • 22