Find-and-Replace Using Regular Expressions and appendReplacement() and appendTail() Methods - Java Regular Expressions

Java examples for Regular Expressions:Replace

Description

Find-and-Replace Using Regular Expressions and appendReplacement() and appendTail() Methods

Demo Code

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

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

    String text = "A test test 125 test test this is a test" + 
              " the value is 100 test test. " + 
              "This is a test." ;

    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(text);/*from  ww  w  .  j a va  2  s.c o  m*/

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

      // Convert the text into an integer for comparing
      int num = Integer.parseInt(matchedText);

      // Prepare the replacement text
      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);
    } 

    // Append the tail
    m.appendTail(sb); 

    // Display the old and new text
    System.out.println("Old Text: " + text);
    System.out.println("New Text: " + sb.toString());
  } 
}

Result


Related Tutorials