Zetland
Zetland

Reputation: 567

Regex for a five-digit numerical String

I'm currently trying to design a regex for a five-digit numerical String, which will be used to store the number of a flight. It's important that this number is exactly 5 numerical characters long. So far, I've come up with this, but it seems a bit flabby:

@NotNull
@Size(min = 5, max = 6)
@Pattern(regexp = "[0-9]{5}", message = "Please use a number with five digits")
@Column(name = "flight_number")
private String flightNumber;

Namely, things like specifying the minimum and maximum value, when the string must only be 5 characters long seems a bit over-the-top. Can anyone suggest improvements to this?

Upvotes: 1

Views: 5015

Answers (3)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

I would personally feel more comfortable taking advantage of Java's built-in math logic. So I would do something like this:

int flightNumber = ...; // your code assigns this
if (flightNumber < 0 || flightNumber >= 100000) {
    logger.error("Bad input");
}
String flightNumberAsString = String.valueOf(flightNumber);

Upvotes: 0

Soumitri Pattnaik
Soumitri Pattnaik

Reputation: 3556

Try this one, it should do

^\d{5}$

Upvotes: 2

npinti
npinti

Reputation: 52185

The regex you are using: [0-9]{5} is quite close to what you wish to achieve. The problem is that you are just saying match 5 digits.

What you would need to do, would be to simply add the ^ and $ anchors to instruct the regex engine to make sure that the string is made up entirely of what you want. Thus, [0-9]{5} becomes ^[0-9]{5}$ or ^\d{5}$.

Upvotes: 3

Related Questions