Java Reference
In-Depth Information
18
19
// replace 'stars' with 'carets'
20
firstString = firstString.replaceAll( "stars" , "carets" );
21
22
System.out.printf(
23
"\"carets\" substituted for \"stars\": %s%n" , firstString);
24
25
// replace words with 'word'
26
System.out.printf( "Every word replaced by \"word\": %s%n%n" ,
27
firstString.replaceAll( "\\w+" , "word" )
);
28
29
System.out.printf( "Original String 2: %s%n" , secondString);
30
31
// replace first three digits with 'digit'
32
for ( int i = 0 ; i < 3 ; i++)
33
secondString = secondString.replaceFirst( "\\d" , "digit" );
34
35
System.out.printf(
36
"First 3 digits replaced by \"digit\" : %s%n" , secondString);
37
38
System.out.print( "String split at commas: " );
39
String[] results = secondString.split( ",\\s*" ); // split on commas
Arrays.toString(results)
40
System.out.println(
);
41
}
42
} // end class RegexSubstitution
Original String 1: This sentence ends in 5 stars *****
^ substituted for *: This sentence ends in 5 stars ^^^^^
"carets" substituted for "stars": This sentence ends in 5 carets ^^^^^
Every word replaced by "word": word word word word word word ^^^^^
Original String 2: 1, 2, 3, 4, 5, 6, 7, 8
First 3 digits replaced by "digit" : digit, digit, digit, 4, 5, 6, 7, 8
String split at commas: ["digit", "digit", "digit", "4", "5", "6", "7", "8"]
Fig. 14.23 | String methods replaceFirst , replaceAll and split . (Part 2 of 2.)
Method replaceAll replaces text in a String with new text (the second argument)
wherever the original String matches a regular expression (the first argument). Line 15
replaces every instance of "*" in firstString with "^" . The regular expression ( "\\*" )
precedes character * with two backslashes. Normally, * is a quantifier indicating that a reg-
ular expression should match any number of occurrences of a preceding pattern. However,
in line 15, we want to find all occurrences of the literal character * —to do this, we must
escape character * with character \ . Escaping a special regular-expression character with \
instructs the matching engine to find the actual character. Since the expression is stored in
a Java String and \ is a special character in Java String s, we must include an additional
\ . So the Java String "\\*" represents the regular-expression pattern \* which matches a
single * character in the search string. In line 20, every match for the regular expression
"stars" in firstString is replaced with "carets" . Line 27 uses replaceAll to replace
all words in the string with "word" .
Search WWH ::




Custom Search