Java
  Home arrow Java arrow Page 9 - Introduction to the Java.util.regex Object...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Moblin 
JMSL Numerical Library 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Introduction to the Java.util.regex Object Model
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 7
    2005-08-18

    Table of Contents:
  • Introduction to the Java.util.regex Object Model
  • public static Pattern compile(String regex, int flags) Throws a PatternSyntaxException
  • public String[] split(CharSequence input)
  • The Matcher Object
  • public int start(int group)
  • public int end(int group)
  • public String group(int group)
  • public boolean find()
  • public Matcher appendReplacement (StringBuffer sb, String replacement)
  • Special Notes
  • New String Rejex-Friendly Methods
  • Summary

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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 );
      }
    }

    More Java Articles
    More By Apress Publishing


     

    Buy this book now. This article is excerpted from chapter three of Java Regular Expressions Taming the Java.util.regex Engine, written by Mehran Habibi (Apress, 2004; ISBN: 1590591070). Check it out at your favorite bookstore. Buy this book now.

    JAVA ARTICLES

    - 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 ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway