Match a single digit character using [0-9] or \d (Java)

Download regex eBook


[0-9] and \d are equivalent patterns (unless your Regex engine is unicode-aware and \d also matches things like ②). They will both match a single digit character so you can use whichever notation you find more readable.

Create a string of the pattern you wish to match. If using the \d notation, you will need to add a second backslash to escape the first backslash.

String pattern = "\\d";

Create a Pattern object. Pass the pattern string into the compile() method.

Pattern p = Pattern.compile(pattern);

Create a Matcher object. Pass the string you are looking to find the pattern in to the matcher() method. Check to see if the pattern is found.

Matcher m1 = p.matcher("0");
m1.matches(); //will return true

Matcher m2 = p.matcher("5");
m2.matches(); //will return true

Matcher m3 = p.matcher("12345");
m3.matches(); //will return false since your pattern is only for a single integer


Contributors: 2
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook