jarosik jarosik - 3 years ago 77
Java Question

Java RegEx that matches exactly 8 digits

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

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?

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

Answer Source

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");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download