恰好匹配 8 位数字的 Java RegEx

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34925218/
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-11-02 23:32:57  来源:igfitidea点击:

Java RegEx that matches exactly 8 digits

javaregex

提问by jarosik

I have a simple RegEx that was supposed to look for 8 digits number:

我有一个简单的 RegEx 应该查找 8 位数字:

String number = scanner.findInLine("\d{8}");

But it turns out, it also matches 9 and more digits number. How to fix this RegEx to match exactly 8 digits?

但事实证明,它也匹配 9 位及更多位数字。如何修复此 RegEx 以精确匹配 8 位数字?

For example: 12345678 should be matched, while 1234567, and 123456789 should not.

例如: 12345678 应该匹配,而 1234567 和 123456789 不应该。

采纳答案by Dalorzo

Try this:

试试这个:

\bis known as word boundary it will say to your regex that numbers end after 8

\b被称为词边界,它会告诉你的正则表达式数字在 8 之后结束

String number = scanner.findInLine("\b\d{8}\b");

回答by A.D

I think this is simple and it works:

我认为这很简单并且有效:

String regEx = "^[0-9]{8}$";
  • ^- starts with

  • [0-9]- use only digits (you can also use \d)

  • {8}- use 8 digits

  • $- End here. Don't add anything after 8 digits.

  • ^- 以。。开始

  • [0-9]- 仅使用数字(您也可以使用\d

  • {8}- 使用 8 位数字

  • $- 到此结束。8 位数字后不要添加任何内容。

回答by Wiktor Stribi?ew

Your regex will match 8 digits anywhere in the string, even if there are other digits after these 8 digits.

您的正则表达式将匹配字符串中任何位置的 8 位数字,即使这 8 位数字之后还有其他数字。

To match 8 consecutive digits, that are not enclosed with digits, you need to use lookarounds:

要匹配未用数字括起来的 8 个连续数字,您需要使用lookarounds

String reg = "(?<!\d)\d{8}(?!\d)";

See the regex demo

查看正则表达式演示

Explanation:

说明

  • (?<!\d)- a negative lookbehind that will fail a match if there is a digit before 8 digits
  • \d{8}8 digits
  • (?!\d)- a negative lookahead that fails a match if there is a digit right after the 8 digits matched with the \d{8}subpattern.
  • (?<!\d)- 如果 8 位数字之前有一位数字,则负向后视将导致匹配失败
  • \d{8}8位
  • (?!\d)- 如果在与\d{8}子模式匹配的 8 位数字之后有一个数字,则匹配失败的负前瞻。