Java Pattern验证注释和util Regex模式表现不同

我有一个正则表达式

^(?=[a-zA-Z0-9,!@#$&*()_'+-=<>.?{}\\[\\]|; :\\s]*$)(?!.*[/])

我通过两种方法为字符串“hello”尝试了正则表达式:

> java.util.regex.Pattern:将通过测试
> javax.validation.constraints.Pattern(annotation):会抛出一个无效值存在的错误.

有谁知道为什么这两个表现不同?

最佳答案 至少对于你给出的测试字符串“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]*$)(?!.*[/])"
点赞