// Fig. 11.23: RegexSubstitution.java // Using methods replaceFirst, replaceAll and split. import javax.swing.*; public class RegexSubstitution { public static void main( String args[] ) { String firstString = "This sentence ends in 5 stars *****"; String secondString = "1, 2, 3, 4, 5, 6, 7, 8"; String output = "Original String 1: " + firstString; // replace '*' with '^' firstString = firstString.replaceAll( "\\*", "^" ); output += "\n^ substituted for *: " + firstString; // replace 'stars' with 'carets' firstString = firstString.replaceAll( "stars", "carets" ); output += "\n\"carets\" substituted for \"stars\": " + firstString; // replace words with 'word' output += "\nEvery word replaced by \"word\": " + firstString.replaceAll( "\\w+", "word" ); output += "\n\nOriginal String 2: " + secondString; // replace first three digits with 'digit' for ( int i = 0; i < 3; i++ ) secondString = secondString.replaceFirst( "\\d", "digit" ); output += "\nFirst 3 digits replaced by \"digit\" : " + secondString; output += "\nString split at commas: ["; String[] results = secondString.split( ",\\s*" ); // split on commas for ( int i = 0; i < results.length; i++ ) output += "\"" + results[ i ] + "\", "; // output results // remove the extra comma and add a bracket output = output.substring( 0, output.length() - 2 ) + "]"; JOptionPane.showMessageDialog( null, output ); System.exit( 0 ); } // end method main } // end class RegexSubstitution /* ************************************************************************** * (C) Copyright 1992-2003 by Deitel & Associates, Inc. and * * Prentice Hall. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * ************************************************************************** */