Java - Regular Expressions Find and Replace

Introduction

Java regular expression can do find and replace action via the following two methods.

Matcher appendReplacement(StringBuffer sb, String replacement)
StringBuffer appendTail(StringBuffer sb)

Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] args) {
    String regex = "\\b\\d+\\b";
    StringBuffer sb = new StringBuffer();
    String replacementText = "";
    String matchedText = "";

    String text = "The tutorial has 125 topics and exerciese that is listed across 100 sections. "
        + "There are 75 chapters.";

    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(text);//from w  w w  . j a v  a 2s.  co  m

    while (m.find()) {
      matchedText = m.group();

      int num = Integer.parseInt(matchedText);
      if (num == 100) {
        replacementText = "a hundred";
      } else if (num < 100) {
        replacementText = "less than a hundred";
      } else {
        replacementText = "more than a hundred";
      }

      m.appendReplacement(sb, replacementText);
    }
    m.appendTail(sb);
    System.out.println("Old Text: " + text);
    System.out.println("New Text: " + sb.toString());
  }
}

Result