Reputation: 843
I'm using the below regular expression:
Pattern testPattern= Pattern.compile("^[1-9][0-9]{14}");
Matcher teststring= testPattern.matcher(number);
if(!teststring.matches())
{
error("blah blah!");
}
My requirements are:
Am I missing anything in regex?
Upvotes: 15
Views: 72771
Reputation: 39532
/^[1-9][0-9]{9,14}$/
will match any number from 10 to 15 digits.
Autopsy:
^
- this MUST be the start of the text[1-9]
- any digit between 1 and 9[0-9]{9,14}
- any digit between 0 and 9 matched 9 to 14 times$
- this MUST be the end of the textUpvotes: 10
Reputation:
Or, an alternative so later you have an at-a-glance look -
^(?!0)\d{10,15}$
Upvotes: 2
Reputation: 213253
With "^[1-9][0-9]{14}"
you are matching 15
digit number, and not 10-15
digits. {14}
quantifier would match exactly 14
repetition of previous pattern. Give a range there using {m,n}
quantifier:
"[1-9][0-9]{9,14}"
You don't need to use anchors with Matcher#matches()
method. The anchors are implied. Also here you can directly use String#matches()
method:
if(!teststring.matches("[1-9][0-9]{9,14}")) {
// blah! blah! blah!
}
Upvotes: 21
Reputation: 785156
To match a 10-15 digit number which should not start with 0
Use end of line anchor $
in your regex with limit between 9 to 14:
Pattern.compile("^[1-9][0-9]{9,14}$");
Upvotes: 1