0

I'm getting a phone number from an external API call and I'm trying to detect if it is indeed a number (I don't care at this point if it's a valid phone number). For simplicity's sake, I tried:

String number = phone.replace("+", "").replace(" ", "").trim();
if (number.matches("[0-9]+")) {
    return true;
}

The string I'm getting in number is something like ‪331234212453 but matches returns false. What is weird is that when I inspect the number variable, copy its value and try:

‪"331234212453".matches("[0-9]+")

It still does not work. Now if I type those same numbers and use matches then I get it to work. Could there be some kind of encoding messing up with the string? And if so how do I fix it?

Edit: Forgot to say that I tried number.matches("\\d+") and it also does not work.

Ricardo
  • 7,785
  • 8
  • 40
  • 60

1 Answers1

2

1st of all when you want to clear all whitespaces you usually dont want to settle for just space. this is much safer:

replaceAll("\\s+","")

as it removes any number of consecutive whitespace characters, and not just spaces. next up, there's a digit class in java regexp syntax, so you could try

matches("\\d+")

also - notice the difference between replace() (which deals with chars) and replaceAll() (which deals in strings and patterns)

radai
  • 23,949
  • 10
  • 71
  • 115
  • Thanks. Forgot to say that I had tried with `number.matches("\\d+")` but it also doesn't work. – Ricardo Dec 14 '13 at 14:53
  • @OliCharlesworth - OP did not provide specific examples of failing input, so we're left guessing – radai Dec 14 '13 at 14:53
  • @radai What do you mean by example? I put the number I'm trying to match in my question. Here is a direct copy from one that is not working in my inspector when I try it, not sure it will matter here: `"‪9302".matches("\\d+")`. This is returning false for me there. – Ricardo Dec 14 '13 at 14:56
  • @radai and using `replaceAll("\\s+","")` does not help either. – Ricardo Dec 14 '13 at 15:03