-1

So i have this project where i need to write a mutator method that changes a person's phone number only if the phone number contains numbers from 0 to 9 and no letters or any other things. The type of the phone number is string and i tried using conditional statements. If the mobile contains anything other than numbers then nothing should happen. this is what i got so far:

public void setMobile(String mobile) {
if(mobile.matches("[a-zA-z]+")){
 }
 else{      
        this.mobile = mobile;
 }

}

thanks

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Omri Ram
  • 3
  • 3
  • 1
    What is your question? But let me ask you a question: If you want to check is string is all digits (0-9), why not check that, i.e. `matches("[0-9]+")`?\ – Andreas Apr 04 '17 at 04:52
  • Possible duplicate of [How to check if a String is numeric in Java](http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java) – soorapadman Apr 04 '17 at 04:55

2 Answers2

2

You regex pattern should be [0-9]+

prasanth
  • 3,502
  • 4
  • 28
  • 42
0

If you are looking for anything that isn't a number then the pattern is \D. That just means non-digit and is a shorthand for [^0-9]

See http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

sprinter
  • 27,148
  • 6
  • 47
  • 78