androidNewbie
androidNewbie

Reputation: 49

Detecting whitespace in Java String regex

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?

Upvotes: 0

Views: 126

Answers (2)

Keppil
Keppil

Reputation: 46209

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}"))) {

Upvotes: 2

Danny Daglas
Danny Daglas

Reputation: 1491

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

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

Upvotes: 1

Related Questions