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.
Next: Comparing Regex and Perl >>
More Java Articles
More By Apress Publishing
|
This article is excerpted from 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.
|
|