0

I am testing a postcode which should begin with two letters ('U' and 'S'), followed by up to two numbers. This works find but my problem is detecting any white space that may follow this. I do not want to permit any whitespace after these have been input. I have used the following code:

              while(!(postcode.matches("([U][S])([0-9]{1,2})+!(\\s)"))){

The above code seems to allow any white spaces after the permitted string. Any help would be much appreciated, thanks?

2 Answers 2

2

Since you use matches(), there is no need to explicitly check that there are no spaces. If there is something following the number(s) it will not match.

You can simplify your expression a bit though. Just do:

while(!(postcode.matches("US[0-9]{1,2}"))) {
Sign up to request clarification or add additional context in comments.

Comments

1

Anchor it with a $ at the end of the regex may work:

while(!(postcode.matches("([U][S])([0-9]{1,2})+$"))){

2 Comments

The $ anchor does nothing when you use matches() here.
Rightly so. I just checked the API. Thanks!

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.