Zeon
Zeon

Reputation: 338

Should I use a Java Regex Pattern or simple System Format?

I'm currently trying to to set up a program so the user must enter a specific string of characters for example DeskID followed by 2-3 ints, thus: DeskNO10 or DeskNO42

At the moment, I have tried:

if(Pattern.matches("[DeskNO0-9]",desk)) {
    System.out.println("Accepted");
} else {
    System.out.println("Rejected");
}

This doesn't work - is there any suggestions I could make it work or would it be advisable, if I just use a simple println statement using %s and %2d

Upvotes: 0

Views: 48

Answers (3)

m.cekiera
m.cekiera

Reputation: 5395

try with:

if(Pattern.matches("DeskNO[0-9]{2,3}",desk))

the [DeskNO0-9] is a character class, so it match only one character from within brackets like D, e, 9, etc., this is why it doesn't work.

With DeskNO[0-9]{2,3} the DeskNO is an obligatory part, and [0-9]{2,3} means it should be followed with two or three digits.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

Your regex uses a character class, i.e. the thing enclosed in square brackets. This means that the expression would accept any single character defined in the square brackets, i.e. D, e, s, k, N, O, 0, 1, ..., 9. This is certainly not what you want.

The correct regex would be

"DeskNO\\d{2,3}"

However, the choice of the approach is up to you: regex may be too much for the job that simple. You could test if the string startsWith("DeskNO"), then take the suffix with substring(6), and check if it's two or three digits.

Upvotes: 2

Reimeus
Reimeus

Reputation: 159784

You could do

if (desk.matches("DeskNO\\d{2,3}")) {

Upvotes: 2

Related Questions