Java Reference
In-Depth Information
Quantifier
Matches
Matches zero or more occurrences of the pattern.
*
+
Matches one or more occurrences of the pattern.
?
Matches zero or one occurrences of the pattern.
{ n }
Matches exactly n occurrences.
{ n ,}
Matches at least n occurrences.
{ n , m }
Matches between n and m (inclusive) occurrences.
Fig. 14.22 | Quantifiers used in regular expressions.
All of the quantifiers are greedy . This means that they'll match as many occurrences
as they can as long as the match is still successful. However, if any of these quantifiers is
followed by a question mark ( ? ), the quantifier becomes reluctant (sometimes called lazy ).
It then will match as few occurrences as possible as long as the match is still successful.
The zip code (line 40 in Fig. 14.20) matches a digit five times. This regular expression
uses the digit character class and a quantifier with the digit 5 between braces. The phone
number (line 46 in Fig. 14.20) matches three digits (the first one cannot be zero) followed
by a dash followed by three more digits (again the first one cannot be zero) followed by
four more digits.
String method matches checks whether an entire String conforms to a regular
expression. For example, we want to accept "Smith" as a last name, but not "9@Smith#" .
If only a substring matches the regular expression, method matches returns false .
Replacing Substrings and Splitting Strings
Sometimes it's useful to replace parts of a string or to split a string into pieces. For this
purpose, class String provides methods replaceAll , replaceFirst and split . These
methods are demonstrated in Fig. 14.23.
1
// Fig. 14.23: RegexSubstitution.java
2
// String methods replaceFirst, replaceAll and split.
3
import java.util.Arrays;
4
5
public class RegexSubstitution
6
{
7
public static void main(String[] args)
8
{
9
String firstString = "This sentence ends in 5 stars *****" ;
10
String secondString = "1, 2, 3, 4, 5, 6, 7, 8" ;
11
12
System.out.printf( "Original String 1: %s%n" , firstString);
13
14
// replace '*' with '^'
15
firstString = firstString.replaceAll( "\\*" , "^") ;
16
17
System.out.printf( "^ substituted for *: %s%n" , firstString);
Fig. 14.23 | String methods replaceFirst , replaceAll and split . (Part 1 of 2.)
 
Search WWH ::




Custom Search