0

I am new here and I have a problem with a code.

I have a String of 5 characters, and this is what I've come up with

public static boolean isNumber(String strng) {
    return (strng.contains("[0-9]+"));
}

public static void main(String[] args) {
     String strng; 
     Scanner strong = new Scanner(System.in);


while (isNumber(dato) == true && dato.length() != 5){
        System.out.println("Isnt a correct id number");
        strng = strong.nextLine();

    }

But with this I can introduce a dot or a semi-colon, I tried with [a-zA-Z]+ and the boolean in false but isn't work I'm searching only for numbers from 0 to 9.

Any clue for this?

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
Mathew Euler
  • 11
  • 1
  • 1
  • 1
    `strng.contains("[0-9]+")` returns `true` for inputs that has digits, but doesn't check that it has *only* digits. – Maroun May 19 '15 at 13:40
  • 1
    @MarounMaroun No, it will not. `strng.contains("[0-9]+")` returns `true` only if the string literally contains `[0-9]+`. The `contains` method does not take a regular expression. – Jesper May 19 '15 at 13:46
  • @Jesper You're right. `matches` accepts `CharSequence` and not a regex string. Thanks. – Maroun May 19 '15 at 13:47

2 Answers2

7

strng.contains("[0-9]+") should rather be strng.matches("[0-9]+")

This will test your strng to have one or more digits.

If you want your string to match exactly five digits, then you'll have to use the "[0-9]{5}" pattern.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
5

You can check the content and the length with your regex:

strng.matches("[0-9]{5}")

This will return true for strings of exactly 5 characters, containing only digit characters.

Armand
  • 23,463
  • 20
  • 90
  • 119