我有正则表达式
^(?=[a-zA-Z0-9,!@#$&*()_'+-=<>.?{}\\[\\]|; :\\s]*$)(?!.*[/])
我通过两种方法为字符串"hello"
尝试了正则表达式:
java.util.regex.Pattern
:将通过测试javax.validation.constraints.Pattern
(注释):会抛出无效值存在的错误。有没有人知道为什么这两个表现不同?
答案 0 :(得分:1)
至少对于你给定的"hello"
测试字符串,似乎两个正则表达式的行为相同,所以很难知道你遇到了什么,没有进一步的信息。
这个简短的程序测试两者。样本输出在下面给出。
public class RegexTest {
static final String REGEX = "^(?=[a-zA-Z0-9,!@#$&*()_'+-=<>.?{}\\[\\]|; :\\s]*$)(?!.*[/])";
static final String TEST = "hello";
public static class TestObject {
@javax.validation.constraints.Pattern(regexp=REGEX)
String name;
}
public static void main(String[] args) {
test1();
test2();
}
public static void test1() {
java.util.regex.Pattern p = java.util.regex.Pattern.compile(REGEX);
Matcher m = p.matcher(TEST);
System.out.println(m.matches()); // false, ie, doesn't match
}
public static void test2() {
TestObject to = new TestObject();
to.name = TEST;
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<TestObject>> violations = validator.validate(to);
for(ConstraintViolation<TestObject> violation : violations) {
System.out.println(violation.getMessage()); // One violation, "must match"
}
}
}
false
INFO o.h.validator.internal.util.Version - HV000001: Hibernate Validator 5.2.4.Final
must match "^(?=[a-zA-Z0-9,!@#$&*()_'+-=<>.?{}\[\]|; :\s]*$)(?!.*[/])"