Checking a number with regular expressions in Java
I have a numb开发者_开发技巧er "8756342536"
. I want to check whether the number starts with "8"
, contains 10 digits all of it is numeric, using regular expression.
What pattern would I need for this scenario in Java? Thanks in advance.
Use String's matches(...) method:
boolean b = "8756342536".matches("8\\d{9}");
Use this expression:
^8\d{9}$
meaning an 8 followed by exactly 9 digits. So for example:
String number = ...
if (number.matches("^8\\d{9}$")) {
// it's a number
}
Given the number is in String
form:
String number = "8756342536";
boolean match = number.matches ("^[8][0-9]{9}$");
精彩评论