cxyz
cxyz

Reputation: 843

Regex to match 10-15 digit number

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:

  1. To match a 10-15 digit number which should not start with 0 and rest all digits should be numeric.
  2. If a 10-15 digit number is entered which starts with zero then teststring does not match with the pattern.my validation error blah blah is displayed.
  3. My problem is if I enter 10-15 digit number which does not start with zero then also validation error message gets displayed.

Am I missing anything in regex?

Upvotes: 15

Views: 72771

Answers (4)

h2ooooooo
h2ooooooo

Reputation: 39532

/^[1-9][0-9]{9,14}$/ will match any number from 10 to 15 digits.

DEMO

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 text

Upvotes: 10

user557597
user557597

Reputation:

Or, an alternative so later you have an at-a-glance look -

^(?!0)\d{10,15}$

Upvotes: 2

Rohit Jain
Rohit Jain

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

anubhava
anubhava

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

Related Questions