0

I'm trying to check if a my substring within my teleInput string contain numbers but I can't seem to get it return true. The results always ends up as false, what am I doing wrong.

String teleInput = "(555)555-5555";
boolean returntT = teleInput.substring(1,3).matches(".*[0-9].*");

I'm an extreme beginner so I don't know if I'm missing something obvious, like mixing methods or maybe something is wrong with the rest of my code, either way, I would really appreciate the help!

TinaE
  • 11
  • 1
  • 1
  • 1
    This could be interesting for you http://stackoverflow.com/questions/3507162/most-elegant-isnumeric-solution-for-java – G. Bach Feb 02 '13 at 03:57

3 Answers3

2

Your problem is your substring - you are only returning two characters: the second parameter is the index up to, but not including, the last character. To get 3 characters, you need:

teleInput.substring(1,4)

So try this (notice that matches only needs to check that it's "all digits", because the length is already know to be 3):

teleInput.substring(1,4).matches("\\d*");

Or just forget substring and use matches alone:

teleInput.matches(".\\d{3}.*");

Which is the regex for "any character then 3 digits then anything".

But you can validate the entire input in one line:

teleInput.matches("(.\\d{3}){3}\\d");

You might have to read up on regex to understand this pattern, but it works!


Note: matches() must match the entire string to be true.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

If you want to check if the 2nd character in your string is number, you can do it like this:

String teleInput = "(555)555-5555";

boolean returntT = teleInput.substring(1,2).matches("[0-9]");
Rob
  • 4,733
  • 3
  • 32
  • 29
M.Sanad
  • 51
  • 1
  • 3
0

Instead of this line:

boolean returntT = teleInput.substring(1,3).matches(".*[0-9].*");

You should be doing:

boolean returntT = teleInput.substring(1,3).matches("[0-9]+");

OR this:

boolean returntT = teleInput.substring(1,3).matches("\\d{2}");

Regex [0-9]+ will make sure that the given input has only 1 or more digits in it. For good tutorial on regex read: http://www.regular-expressions.info/

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • You never need ^ or $ in matches() – Bohemian Aug 09 '13 at 21:25
  • 1
    Actually, it's really important to remember that matches must match the whole string - all other languages I can think of only need to match *part* of the string for their equivalent method - java is unusual in this respect so it's easy to forget – Bohemian Aug 09 '13 at 21:47