dwix dwix - 7 months ago 29
Java Question

@Pattern regex allowing only : numbers & empty String & numbers beginning by 0

I'm using the @Pattern annotation on a String field in my Entity, with a regex allowing numbers or empty strings only, but I need to allow numbers beginning by 0 too.

This is the pattern I'm using now :

@Pattern(message="Entrez un nombre" , regexp = "[+-]?(([1-9][0-9]*)|(0))([.,][0-9]+)?|(^$)")
private String BSCId;

Thank you.


Try this:


This allows numbers to begin with 0, and also allows the string to be empty by making the whole string optional.

  • [+-]?(\d+) match optional + or - and then match 1 to infinity digits
  • ([,.]\d+)? match , or . and then one to infinity digits. Make the whole fraction optional, so as integers could also be matched.
  • (?:...)? make everything optional (so as empty string would match as per requirements), without creating a capture group.