Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match 10-15 digit number

Tags:

java

regex

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?

like image 922
cxyz Avatar asked Oct 16 '13 18:10

cxyz


People also ask

How do I match a range of numbers in regex?

With regex you have a couple of options to match a digit. You can use a number from 0 to 9 to match a single choice. Or you can match a range of digits with a character group e.g. [4-9]. If the character group allows any digit (i.e. [0-9]), it can be replaced with a shorthand (\d).

Which regex matches one or more digits?

+: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

How do I check if a number is only in regex?

If you want to get only digits using REGEXP, use the following regular expression( ^[0-9]*$) in where clause. Case 1 − If you want only those rows which have exactly 10 digits and all must be only digit, use the below regular expression.


1 Answers

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!
}
like image 123
Rohit Jain Avatar answered Sep 19 '22 06:09

Rohit Jain