-1

I'm trying to figure out how the str.replaceAll(string, newString) method works. I know how to use it, but I'm trying to figure out what goes on inside the method. Does it use multiple for loops and strings, or something more advanced than that? Ideas, pseudocode, and code examples would be lovely.

PS I've already searched this up, but it only shows how to use it, not how it works.

GBlodgett
  • 12,704
  • 4
  • 31
  • 45
bob larry
  • 67
  • 3

1 Answers1

1

According to the source code for String#replaceAll:

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

It creates a Pattern and uses regex to replace the target with the replacement.


In case you want to know about the Matcher#replaceAll call:

public String replaceAll(String replacement) {
    reset();
    boolean result = find();
    if (result) {
        StringBuffer sb = new StringBuffer();
        do {
            appendReplacement(sb, replacement);
            result = find();
        } while (result);
        appendTail(sb);
        return sb.toString();
    }
    return text.toString();
}
GBlodgett
  • 12,704
  • 4
  • 31
  • 45