Home arrow Java arrow Page 9 - Introduction to the Java.util.regex Object Model
JAVA

Introduction to the Java.util.regex Object Model


If you have ever wanted to know all about the Pattern and Matcher classes of Java's new java.util.regex package, this article is an excellent place to start. It is taken from chapter 2 of the book Java Regular Expressions: Taming the java.util.regex Engine, written by Mehran Habibi (Apress, 2004; ISBN: 1590591070).

Author Info:
By: Apress Publishing
Rating: 4 stars4 stars4 stars4 stars4 stars / 15
August 18, 2005
TABLE OF CONTENTS:
  1. · Introduction to the Java.util.regex Object Model
  2. · public static Pattern compile(String regex, int flags) Throws a PatternSyntaxException
  3. · public String[] split(CharSequence input)
  4. · The Matcher Object
  5. · public int start(int group)
  6. · public int end(int group)
  7. · public String group(int group)
  8. · public boolean find()
  9. · public Matcher appendReplacement (StringBuffer sb, String replacement)
  10. · Special Notes
  11. · New String Rejex-Friendly Methods
  12. · Summary

print this article
SEARCH DEVARTICLES

Introduction to the Java.util.regex Object Model - public Matcher appendReplacement (StringBuffer sb, String replacement)
(Page 9 of 12 )

There will be times when you’ll prefer to use a StringBuffer instead of a String when working with regular expressions. This might be for performance, utility, or other reasons. Fortunately, the java.util.regex package offers the appendReplacement and appendTail methods for doing so. This section focuses on the appendReplacement method.

Simply speaking, appendReplacement allows you to create a StringBuffer based on the contents of your Pattern and Matcher objects. Say you want to swap out Smith for Bond in the My name is Bond. James Bond. I would like a martini., and you want the results stored in a StringBuffer. To use appendReplacement, you must first create a Pattern and a corresponding Matcher. For this example’s purposes, you’ll use Bond:

Pattern pattern = Pattern.compile("Bond");

Also, you’ll work with the candidate string My name is Bond. James Bond. I would like a martini.:

Matcher matcher =
 pattern.matcher("My name is Bond. James Bond. I would like a martini.");

Next, you call the find method, so that the Matcher can start to parse the candidate String. The first time you call find, the Matcher simply parses enough of the candidate String such that the first match, if any, is found. This parsed region is boxed in the following image:

 

Recall that the boxed region is the only part of the candidate string the Matcher is currently aware of.

Then you’ll call the appendReplacement method, which populates the StringBuffer sb with everything in the boxed region shown in the preceding image, except that Smith is swapped out for Bond. Therefore, your StringBuffer now contains My name is Smith.

One last thing bears mentioning. Internally, the Matcher object maintains an append position. This append position is state information maintained by the Matcher object for the sake of the StringBuffer object. It records the position in the StringBuffer that the last call to appendReplacement read from. Of course, the append position is initially 0, as shown in the following image:

 

After you call appendReplacement, the append position is moved forward to just after the match, as shown in the following image. This is the same position that the matcher.end() method would return.

 

Next, you call matcher.find() again, so that the current position under consideration becomes the boxed region highlighted in the following image:

 

You then call appendReplacement again, thus appending.James Smith to the StringBuffer. Remember, because this is a replacement method, it automatically replaces Bond with Smith. The content of the StringBuffer becomes My name is Smith. James Smith, and the append position is moved forward, as shown in the following image:

 

Your mission is accomplished. The complete code listing is displayed in Listing 2-20.

Listing 2-20. appendReplacement Method Example

import java.util.regex.*;
import java.util.*;
/**
 * Demonstrates usage of the
 * Matcher.appendReplacement method
 */
public class Scrap
{
  public static void main(String args[]){
     test();
  }
  public static void test(){
    
//create a Pattern
      Pattern p = Pattern.compile("Bond");
      //create a StringBuffer
      StringBuffer sb =new StringBuffer();
    
//create the candidate Strings
     String candidateString =
     "My name is Bond. James Bond. I would like a martini.";
    
String replacement = "Smith";
     //Attempt to match the first candidate String
     Matcher matcher = p.matcher(candidateString); 
     matcher.find();
    
//populate the StringBufffer
     matcher.appendReplacement(sb,replacement);
    
//Attempt to match the second candidate String
     Matcher matcher = p.matcher(candidateString); 
     matcher.find();
    
//populate the StringBufffer
     matcher.appendReplacement(sb,replacement);
    
//display the output for the candidate
     String msg = sb.toString();
    
System.out.println(msg.length());
     System.out.println( msg );
  }
}


blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials