Reputation: 1257
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.
Upvotes: 0
Views: 2178
Reputation: 19015
Try this:
^(?:[+-]?(\d+)([,.]\d+)?)?$
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.Upvotes: 2