实际示例
实际的字符串验证场景
graph TD
A[实际验证场景] --> B[用户注册]
A --> C[表单输入验证]
A --> D[数据处理]
1. 用户注册验证
电子邮件验证示例
public class UserRegistrationValidator {
public static boolean validateRegistration(String username, String email, String password) {
return isValidUsername(username)
&& isValidEmail(email)
&& isStrongPassword(password);
}
private static boolean isValidUsername(String username) {
return username!= null
&& username.length() >= 3
&& username.length() <= 20
&& username.matches("^[a-zA-Z0-9_]+$");
}
private static boolean isValidEmail(String email) {
String emailRegex = "^[A-Za-z0-9+_.-]+@(.+)$";
return email!= null && email.matches(emailRegex);
}
private static boolean isStrongPassword(String password) {
return password!= null
&& password.length() >= 8
&& password.matches("^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$");
}
}
2. 表单输入验证
信用卡号码验证
public class PaymentValidator {
public static boolean validateCreditCardNumber(String cardNumber) {
// 去除空格和连字符
String cleanedNumber = cardNumber.replaceAll("[\\s-]", "");
// 检查长度和是否为数字
if (!cleanedNumber.matches("\\d{13,19}")) {
return false;
}
// 卢恩算法
return validateLuhnAlgorithm(cleanedNumber);
}
private static boolean validateLuhnAlgorithm(String number) {
int sum = 0;
boolean alternate = false;
for (int i = number.length() - 1; i >= 0; i--) {
int digit = Character.getNumericValue(number.charAt(i));
if (alternate) {
digit *= 2;
if (digit > 9) {
digit -= 9;
}
}
sum += digit;
alternate =!alternate;
}
return (sum % 10 == 0);
}
}
3. 数据处理验证
CSV数据清理
public class DataProcessor {
public static String cleanCSVData(String rawData) {
// 去除特殊字符
String cleanedData = rawData.replaceAll("[^a-zA-Z0-9,.]", "");
// 限制长度
if (cleanedData.length() > 100) {
cleanedData = cleanedData.substring(0, 100);
}
return cleanedData;
}
public static boolean isValidCSVRow(String row) {
// 验证CSV行格式
return row!= null
&&!row.trim().isEmpty()
&& row.split(",").length > 0;
}
}
验证策略比较
场景 |
验证方法 |
复杂度 |
性能 |
用户名 |
正则表达式 + 长度检查 |
低 |
高 |
电子邮件 |
正则表达式模式 |
中等 |
中等 |
密码 |
多个条件 |
高 |
低 |
信用卡 |
卢恩算法 |
高 |
中等 |
字符串验证的最佳实践
- 针对每个用例使用适当的验证方法
- 实施多个验证检查
- 提供清晰的错误消息
- 考虑性能影响
- 在处理前清理输入
错误处理示例
public class ValidationHandler {
public static void processUserInput(String input) {
try {
if (!isValidInput(input)) {
throw new IllegalArgumentException("无效输入");
}
// 处理有效输入
} catch (IllegalArgumentException e) {
System.err.println("验证错误: " + e.getMessage());
}
}
private static boolean isValidInput(String input) {
// 全面的验证逻辑
return input!= null
&&!input.trim().isEmpty()
&& input.length() <= 50;
}
}
通过掌握这些实际的验证技术,开发人员可以使用LabEx Java编程实践创建健壮且安全的应用程序。