Java 正则表达式匹配 10-15 位数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19410950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:55:58  来源:igfitidea点击:

Regex to match 10-15 digit number

javaregex

提问by cxyz

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.
  1. 要匹配不应以 0 开头的 10-15 位数字,其余所有数字都应为数字。
  2. 如果输入以零开头的 10-15 位数字,则测试字符串与模式不匹配。显示我的验证错误等等。
  3. 我的问题是,如果我输入不以零开头的 10-15 位数字,那么也会显示验证错误消息。

Am I missing anything in regex?

我在正则表达式中遗漏了什么吗?

采纳答案by Rohit Jain

With "^[1-9][0-9]{14}"you are matching 15digit number, and not 10-15digits. {14}quantifier would match exactly 14repetition of previous pattern. Give a range there using {m,n}quantifier:

"^[1-9][0-9]{14}"您匹配的15数字是数字,而不是10-15数字。{14}量词将完全匹配14先前模式的重复。使用{m,n}量词给出一个范围:

"[1-9][0-9]{9,14}"

You don't need to use anchorswith Matcher#matches()method. The anchors are implied. Also here you can directly use String#matches()method:

你并不需要使用Matcher#matches()方法。锚点是隐含的。在这里你也可以直接使用String#matches()方法:

if(!teststring.matches("[1-9][0-9]{9,14}")) {
    // blah! blah! blah!
}

回答by anubhava

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

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:

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

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

回答by h2ooooooo

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

/^[1-9][0-9]{9,14}$/将匹配 10 到 15 位数字之间的任何数字。

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
  • ^- 这必须是文本的开始
  • [1-9]- 1 到 9 之间的任何数字
  • [0-9]{9,14}- 0 到 9 之间的任何数字匹配 9 到 14 次
  • $- 这必须是文本的结尾

回答by h2ooooooo

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

或者,另一种选择,以便稍后您一目了然-

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

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