Write the String
literal you would need to specify the
regular expression \+?[0-9]+\.[0-9]*
"\\+?[0-9]+\\.[0-9]*"
replaceAll()
Sometimes a regular expression is used to match just a portion of a string. The
replaceAll(String RE, String replacement)
method
constructs a new String
where the parts of the original string
that match RE
are replaced with replacement
.
If nothing matches, the new string is an unchanged copy of the original string.
This code fragment
String line = "Dear XXXX, How would you like million dollar check made out to XX?" ; String filledIn = line.replaceAll( "XX+", "Bill Smith");
creates a new string, referenced by filledIn
,
containing the characters
"Dear Bill Smith, How would you like million dollar check made out to Bill Smith?" ;
The following almost-practical program reads lines of text from standard input, replaces all occurences of two or more Xs with text from the command, and writes the modified lines to standard output. The program can create a "personalized" file from a template file when file redirection is used on the command line:
C:\> java Personalize "Bill Smith" < templateFile.txt > newFile.txt
import java.util.Scanner; class Personalize { public static void main (String[] args) { String line; String name = args[0]; Scanner scan = new Scanner( System.in ); while ( scan.hasNextLine() ) { line = scan.nextLine(); String filledIn = line.replaceAll( "XX+", name ); System.out.println( filledIn ); } } }
If you need to review file redirection, see chapter 21 in the on line Java notes.. If you need to review command line parameters, see chapter 49B in the same Java notes..
By the way, the Scanner
class itself uses regular expressions
in some methods.
More about this in a future chapter.
Could the String
that contains the regular expression
come from the command line?