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.
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.