Search code examples
javaregexhibernatepattern-matchinghibernate-annotations

Multiple Pattern matching in Hibernate Annotation


I need to validate one field for the below case. for this i need to write a regular expression via annotations...

  1. If value is other than (only 9 numeric digits) or (2 numeric digits followed by a hyphen followed by 7 numeric digits)-(show error message 1)

  2. It can't be all the nine digits are zeros.-(show error message 2)


Solution

  • The following regex should do:

    ^(?=.*[1-9])\d{2}-?\d{7}$
    

    Explanation:

    ^             # Start of string
    (?=.*([1-9])) # Assert that there is at least one digit > 0, capture that digit
    \d{2}         # Match any two digits
    -?            # Match an optional hyphen
    \d{7}         # Match any seven digits
    $             # End of string
    

    In order to check if condition 1 or 2 was met, check group number 1 ($1) after the match - if it's undefined, then there was no nonzero digit in the string.