简体   繁体   中英

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?

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!
}

/^[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

或者,一个替代方案,以后您可以一目了然 -

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

To match a 10-15 digit number which should not start with 0

在正则表达式中使用行结束锚$ ,限制在9到14之间:

Pattern.compile("^[1-9][0-9]{9,14}$");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM