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.
match(/(\d{5})/g);
\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ).
The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.
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.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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With