java 正则表达式匹配地址的非法字符
时间: 2024-09-21 10:02:45 浏览: 39
在Java中,正则表达式用于匹配特定模式,如果想验证地址是否包含非法字符,你可以定义一个模式来排除常见的不符合地址规则的字符。例如,地址通常不会包含特殊符号如#、$、%等,空格过多,或者是连续的点(..)等。下面是一个简单的例子:
```java
import java.util.regex.Pattern;
public class AddressValidator {
private static final String ILLEGAL_CHARACTERS = "[#$%^&*()~`|}{[]:;?><,./\\-]+";
private static final Pattern ADDRESS_PATTERN = Pattern.compile("^[a-zA-Z0-9\\. -]{3,}$" + // Allow alphanumeric characters, dots, spaces, and hyphens
"(?!.*[" + ILLEGAL_CHARACTERS + "])"); // Negative lookahead to exclude illegal characters
public static boolean isValidAddress(String address) {
return ADDRESS_PATTERN.matcher(address).matches();
}
阅读全文