0

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

3 Answers 3

2

You could do

if (desk.matches("DeskNO\\d{2,3}")) {
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.