Java Reference
In-Depth Information
Character
Matches
Character
Matches
\d
any digit
any nondigit
\D
\w
any word character
\W
any nonword character
\s
any white-space character
\S
any non-whitespace
character
Fig. 14.19
|
Predefined character classes.
Regular expressions are not limited to these predefined character classes. The expres-
sions employ various operators and other forms of notation to match complex patterns.
We examine several of these techniques in the application in Figs. 14.20 and 14.21, which
validates user input
via regular expressions. [
Note:
This application is not designed to match
all possible valid user input.]
1
// Fig. 14.20: ValidateInput.java
2
// Validating user information using regular expressions.
3
4
public class
ValidateInput
5
{
6
// validate first name
7
public static boolean
validateFirstName(String firstName)
8
{
9
return
firstName.matches(
"[A-Z][a-zA-Z]*"
);
10
}
11
12
// validate last name
13
public static boolean
validateLastName(String lastName)
14
{
15
return
lastName.matches(
"[a-zA-z]+(['-][a-zA-Z]+)*"
);
16
}
17
18
// validate address
19
public static boolean
validateAddress(String address)
20
{
21
return
address.matches(
"\\d+\\s+([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)"
);
22
23
}
24
25
// validate city
26
public static boolean
validateCity(String city)
27
{
28
return
city.matches(
"([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)"
);
29
}
30
31
// validate state
32
public static boolean
validateState(String state)
33
{
Fig. 14.20
|
Validating user information using regular expressions. (Part 1 of 2.)