Java Reference
In-Depth Information
The following code
System.out.println("Java Java Java".replaceFirst("v\\w", "wi"));
displays
Jawi Java Java
There are two overloaded split methods. The split(regex) method splits a string into
substrings delimited by the matches. For example, the following statement
String[] tokens = "Java1HTML2Perl".split("\\d");
splits string "Java1HTML2Perl" into Java , HTML , and Perl and saved in tokens[0] ,
tokens[1] , and tokens[2] .
In the split(regex, limit) method, the limit parameter determines how many times
the pattern is matched. If limit <= 0 , split(regex, limit) is same as split(regex) .
If limit > 0 , the pattern is matched at most limit - 1 times. Here are some examples:
"Java1HTML2Perl" .split( "\\d" , 0 ); splits into Java, HTML, Perl
"Java1HTML2Perl" .split( "\\d" , 1 ); splits into Java1HTML2Perl
"Java1HTML2Perl" .split( "\\d" , 2 ); splits into Java, HTML2Perl
"Java1HTML2Perl" .split( "\\d" , 3 ); splits into Java, HTML, Perl
"Java1HTML2Perl" .split( "\\d" , 4 ); splits into Java, HTML, Perl
"Java1HTML2Perl" .split( "\\d" , 5 ); splits into Java, HTML, Perl
Note
By default, all the quantifiers are greedy . This means that they will match as many
occurrences as possible. For example, the following statement displays JRvaa , since
the first match is aaa .
System.out.println( "Jaaavaa" .replaceFirst( "a+" , "R" ));
You can change a qualifier's default behavior by appending a question mark ( ? ) after it.
The quantifier becomes reluctant , which means that it will match as few occurrences
as possible. For example, the following statement displays JRaavaa , since the first
match is a .
System.out.println( "Jaaavaa" .replaceFirst( "a+?" , "R" ));
 
Search WWH ::




Custom Search