Java RegEx that matches exactly 8 digits

Try this:

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

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

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.


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

To match 8 consecutive digits, that are not enclosed with digits, you need to use 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.

Tags:

Java

Regex