Home arrow Java arrow Page 10 - Regular Expressions
JAVA

Regular Expressions


Regular expressions are a mechanism for telling the Java Virtual Machine (JVM) how to find and manipulate text for you. Using regular expressions to do this is different from the traditional approach. This article compares the two approaches. It is excerpted from Java Regular Expressions: Taming the java.util.regex Engine, written by Mehran Habibi (Apress, 2004; ISBN: 1590591070).

Author Info:
By: Apress Publishing
Rating: 5 stars5 stars5 stars5 stars5 stars / 28
July 28, 2005
TABLE OF CONTENTS:
  1. · Regular Expressions
  2. · Creating Patterns
  3. · Common and Boundary Characters
  4. · Character Classes
  5. · Back References
  6. · Integrating Java with Regular Expressions
  7. · Confirming Name Formats Example
  8. · Finding Duplicate Words Example
  9. · Regular Expression Operations
  10. · Search and Replace
  11. · Comparing Regex and Perl

print this article
SEARCH DEVARTICLES

Regular Expressions - Search and Replace
(Page 10 of 11 )

One of the most powerful features of the new regex package is the ability to search for and replace Strings and substrings. As you may recall, this sort of activity was previously a tedious affair, as it required the use of tokenizers or the use of the String.substring methods, along with a lot of String arithmetic.

Thankfully, those days are over. There are two general ways to do search and replace operations in J2SE. The following example travels the easier path by taking advantage of two new methods added to the String class. (Chapter 4 contains more complex examples that use the Pattern and Matcher classes directly.) The two methods relevant for the following example are as follows:

  • replaceFirst(String regex, String replacement)

  • replaceAll(String regex,String replacement)

The first method, replaceFirst(String regex, String replacement), simply replaces the first occurrence of the regex pattern with the replacement String. The second method, replaceAll, replaces all occurrences of the pattern with the replacement String. I explain these new methods in detail in Chapter 2.

Search and Replace Example

If youíre like me, you probably think about programming more than you should. Say youíre writing an essay on boxing. Further, say you decide to update your essay on boxing programmatically instead of manually. Listing 1-10 shows the code for doing so. The example searches for and replaces some commonly misused phrases from the given paragraph. Output 1-10 shows the result of running the program.

Listing 1-10. StyleSearchAndReplace.java

public class StyleSearchAndReplace{
  public static void main(String args[]){
   
String statement = "The question as to whether the jab is"+
    " superior to the cross has been debated for some time in"+
    " boxing circles. However, it is my opinion that this"+
   
" false dichotomy misses the point. I call your attention"+
    " to the fact that the best boxers often use a combination of"+
    " the two. I call your attention to the fact that Mohammed"+
    " Ali,the Greatest of the sport of boxing, used both. He had"+
    " a tremendous jab, yet used his cross effectively, often,Ē+
    " and well";
   
String newStmt=
    statement.replaceAll("The question as to whether","Whether");
   
newStmt= newStmt.replaceAll(" of the sport of boxing","");
    newStmt=newStmt.replaceAll("amount of success","success");
    newStmt=
   
newStmt.replaceAll("However, it is my opinion that this","This");
   
newStmt= newStmt.replaceAll("a combination of the two","both");
    newStmt= newStmt.replaceAll("This is in spite of the fact that"
     +" the", "The");
    newStmt=
     newStmt.replaceAll("I call your attention to the fact that","");
    System.out.println("BEFORE:\n"+statement + "\n"); 
    System.out.println("AFTER:\n"+newStmt);
  }
}

Output 1-10. Result of Running StyleSearchAndReplace.java

------------------------------------------------------------------
C:\RegEx\Examples\chapter1>java StyleSearchAndReplace BEFORE:
The question as to whether the jab is superior to the cross has been debated for some time in boxing circles. However, it is my opinion that this false dichotomy misses the point. I call your attention to the fact that the best boxers often use a combination of the two. I call your attention to the fact that Mohammed Ali,the Greatest of the sport of boxing, used both. He had a tremendous jab, yet
used his cross effectively,often, and well
AFTER:

Whether the jab is superior to the cross has been debated for some time in boxing circles. This false dichotomy misses the point. the best boxers often use both.
Mohammed Ali,the Greatest, used both. He had a tremendous jab, yet used his cross effectively,often, and well

As Output 1-10 shows, the clarity of the paragraph has improved somewhat as a result of this process.

Splitting a String

There are many mechanisms available for splitting a String, the most obvious being the StringTokenizer. However, splitting a String can be surprisingly complex, because it can require fairly complex criteria. For example, itís easy enough to split a comma-separated file, but what about splitting a word into vowels and consonants? The latter can be ridiculously complicated. Fortunately, regular expressions can be particularly helpful in these sorts of situations, as youíll learn in the following sections.

Splitting a String Example

In English rhetoric, we learn that one of the best ways to strengthen a sentence is to place positives and negatives in opposition. The code in Listing 1-11 takes a sentence and attempts to strengthen it by placing the positives and negatives in opposition. Output 1-11 shows the result.

Listing 1-11. StyleSplitExample.java

public class StyleSplitExample{
 
public static void main(String args[]){
   
String phrase1= "but simple justice, not charity";
   
strengthenSentence(phrase1);
   
String phrase2=
     "but that I love Rome more, not that I love Caesar less";
    strengthenSentence(phrase2);
   
String phrase3=
    "ask what you can do for your country, ask not what your "
   
+ "country can do for you";
   
strengthenSentence(phrase3);
  }
    /**
    
* Splits and rearranges the given String, hopefully to a more
   
* powerful effect.
   
* @param sentence is a String representing the phrase we want to
   
* strengthen.
   
* @returns is a String representing the modified phrase.
    */
    public static String strengthenSentence(String sentence){
      
String retval=null;
      
String[] tokens = null;
     
String splitPattern = ",";
     
tokens= sentence.split(splitPattern);
     
if (tokens==null){
        String msg = "    NO MATCH: pattern:" + sentence
           
+ "\r\n              regex: " + splitPattern;
      }
      else{
       
retval = tokens[1] + ", " + tokens[0]; 
        System.out.println("BEFORE: " + sentence);
        System.out.println("AFTER : " + retval +"\n");
     
}
      return retval;
  }
}

Output 1-11. Result of Running StyleSplitExample.java

------------------------------------------------------------------
C:\RegEx\Examples\chapter1>java StyleSplitExample
BEFORE: but simple justice, not charity
AFTER :  not charity, but simple justice

BEFORE: but that I love Rome more, not that I love Caesar less
AFTER : not that I love Caesar less, but that I love Rome more

BEFORE: ask what you can do for your country, ask not what your country can do for you
AFTER : ask not what your country can do for you, ask what you can do for your country

Conditional String Splitting Example

Regex becomes particularly useful when you have more complete String parsing needs. Itís easy enough to split a string when itís in a well-defined format, such as a comma-delimited file. You donít need regex for that; a StringTokenizer will do just fine. But what if you want to split a string based on, say, a word or any of its synonyms?

Regular expressions can be helpful in these kinds of scenarios because they allow you to qualify complex criteria for effecting a division. Listing 1-12 splits the given phrase based on occurrences of the word compromise or its synonyms. Output 1-12 shows the result of running the program.

Listing 1-12. Split.java

public class Split{
  public static void main(String args[]){
   
String statement = "I will not compromise. I will not "+
    "cooperate. There will be no concession, no conciliation, no "+
    "finding the middle group, and no give and take.";
   
String tokens[] =null;
   
String splitPattern= "compromise|cooperate|concession|"+
    "conciliation|(finding the middle group)|(give and take)";
   
tokens=statement.split(splitPattern);
   
System.out.println("REGEX PATTERN:\n"+splitPattern + "\n");
   
System.out.println("STATEMENT:\n"+statement + "\n");
   
System.out.println("\nTOKENS");
   
for (int i=0; i < tokens.length; i++){
   
System.out.println(tokens[i]);
   
}
 
}
}

Output 1-12. Result of Running Split.java

-----------------------------------------------------------------
C:\RegEx\Examples\chapter1>java Split
REGEX PATTERN: compromise|cooperate|concession|conciliation|(finding the middle group)|(give and take)

STATEMENT:
I will not compromise. I will not cooperate. There will be no concession, no conciliation,
no finding the middle group, and no give and take.

TOKENS:
I will not
. I will not
. There will be no
, no
, no
, and no
.

This example illustrates the new types of possibilities that now exist as part of the standard Java implementation. I discuss more sophisticated splits in Chapters 3 and 4.


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