Java Reference
In-Depth Information
For example,
"Smith".matches("[A-Z][a-zA-Z]{1,24}") returns true .
"Jones123".matches("[A-Z][a-zA-Z]{1,24}") returns false .
Example 5
Java identifiers are defined in Section 2.4, “Identifiers.”
An identifier must start with a letter, an underscore ( _ ), or a dollar sign ( $ ). It cannot
start with a digit.
An identifier is a sequence of characters that consists of letters, digits, underscores
( _ ), and dollar signs ( $ ).
The pattern for identifiers can be described as
[a-zA-Z_$][\\w$]*
Example 6
What strings are matched by the regular expression "Welcome to (Java|HTML)" ? The
answer is Welcome to Java or Welcome to HTML .
Example 7
What strings are matched by the regular expression "A.*" ? The answer is any string that
starts with letter A.
H.3 Replacing and Splitting Strings
The matches method in the String class returns true if the string matches the regular
expression. The String class also contains the replaceAll , replaceFirst , and split
methods for replacing and splitting strings, as shown in Figure H.1.
java.lang.String
+matches(regex: String): boolean
+replaceAll(regex: String, replacement:
String): String
Returns true if this string matches the pattern.
Returns a new string that replaces all matching substrings with
the replacement.
+replaceFirst(regex: String,
replacement: String): String
Returns a new string that replaces the first matching substring
with the replacement.
+split(regex: String): String[]
Returns an array of strings consisting of the substrings split by
the matches.
+split(regex: String, limit: int): String[]
Same as the preceding split method except that the limit
parameter controls the number of times the pattern is applied.
F IGURE H.1
The String class contains the methods for matching, replacing, and splitting strings using regular
expressions.
The replaceAll method replaces all matching substring and the replaceFirst method
replaces the first matching substring. For example, the following code
System.out.println("Java Java Java".replaceAll("v\\w", "wi"));
displays
Jawi Jawi Jawi
 
Search WWH ::




Custom Search