Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java RegEx that matches exactly 8 digits

Tags:

java

regex

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.

like image 884
jarosik Avatar asked Jan 21 '16 13:01

jarosik


People also ask

How does regex Match 5 digits?

match(/(\d{5})/g);

How do you find digits in regex?

\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] ).

What does \\ mean in Java regex?

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.


3 Answers

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.

like image 158
A.D Avatar answered Oct 25 '22 21:10

A.D


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.
like image 9
Wiktor Stribiżew Avatar answered Oct 25 '22 21:10

Wiktor Stribiżew


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");
like image 6
Dalorzo Avatar answered Oct 25 '22 23:10

Dalorzo