新的项目开始了,只能利用闲暇时间调试代码、发博客了。
心得:
常用正则表达式基本都能在网上找到实例,结合实际情况,修改一下就能做到“他山之石,可以攻玉”了。
关键是,我们要通过不断的学习和实践,知道“如何”去修改。
代码如下:
//Fig. 14.21: Validate.java
//Input and validate data from user using the ValidateInput class.
import java.util.Scanner;
public class FirstValidation
{
public static void main(String[] args)
{
String firstName;
String lastName;
String address;
String city;
String state;
String zip;
String phone;
// get user input
Scanner scanner = new Scanner(System.in);
do{
System.out.println("请输入姓:");
firstName = scanner.nextLine();
if (!validateFirstName(firstName))
System.out.println("Invalid first name");
}
while(!validateFirstName(firstName));
do{
System.out.println("请输入名:");
lastName = scanner.nextLine();
if (!validateLastName(lastName))
System.out.println("Invalid last name");
}
while(!validateLastName(lastName));
do{
System.out.println("请输入地址:");
address = scanner.nextLine();
if (!validateAddress(address))
System.out.println("Invalid address");
}
while(!validateAddress(address));
do{
System.out.println("请输入城市:");
city = scanner.nextLine();
if (!validateCity(city))
System.out.println("Invalid city");
}
while(!validateCity(city));
do{
System.out.println("请输入省份:");
state = scanner.nextLine();
if (!validateState(state))
System.out.println("Invalid state");
}
while(!validateState(state));
do{
System.out.println("请输入邮编");
zip = scanner.nextLine();
if (!validateZip(zip))
System.out.println("Invalid zip code");
}
while(!validateZip(zip));
do{
System.out.println("请输入电话号码:");
phone = scanner.nextLine();
if (!validatePhone(phone))
System.out.println("Invalid phone number");
}
while(!validatePhone(phone));
// validate user input and display error message
}
//Fig. 14.20: ValidateInput.java
//Validating user information using regular expressions.
public static boolean validateFirstName(String firstName)
{
//姓:1-2个汉字
return firstName.matches("[\u4e00-\u9fa5]{1,2}");
}
//名:2-4个汉字
public static boolean validateLastName(String lastName)
{
return lastName.matches("[\u4e00-\u9fa5]{2,4}");
}
//地址:仅包含汉字和数字,以汉字开头和结尾,至少包含2个汉字和1位数字
public static boolean validateAddress(String address)
{
return address.matches(
"[\u4e00-\u9fa5]+(\\d+[\u4e00-\u9fa5]+)+");
}
//城市:只能输入2-12个汉字
public static boolean validateCity(String city)
{
return city.matches("[\u4e00-\u9fa5]{2,11}");
}
//省份:只能输入2-9个汉字
public static boolean validateState(String state)
{
return state.matches("[\u4e00-\u9fa5]{2,9}") ;
}
//邮编:共6位数字,1-9开头
public static boolean validateZip(String zip)
{
return zip.matches("[1-9]\\d{5}");
}
//手机号:
public static boolean validatePhone(String phone)
{
return phone.matches("(\\+\\d+)?1[3458]\\d{9}");
}
} // end class ValidateInput