Unicode Digit Classes IsDigit And Regex

Character.isDigit accepts every Unicode decimal digit while regex \d stays ASCII-only until UNICODE_CHARACTER_CLASS upgrades the character classes.

JavaForm Validation

Code

snippet
import java.util.regex.Pattern;

public class DigitClassScope {

    public static void main(String[] args) {
        // U+0663 阿拉伯-印度数字、U+FF11 全角数字:都是 Unicode 十进制数字
        String arabic = "\u0663";
        String fullwidth = "\uFF11";

        // Character.isDigit 覆盖所有 Nd(decimal digit)类别
        System.out.println("isDigit ascii     = " + Character.isDigit('3'));
        System.out.println("isDigit arabic    = " + Character.isDigit(arabic.charAt(0)));
        System.out.println("isDigit fullwidth = " + Character.isDigit(fullwidth.charAt(0)));

        // regex 里 \d 默认只有 ASCII 口径(predefined character classes),
        // 阿拉伯数字不命中
        Pattern ascii = Pattern.compile("\\d");
        System.out.println("ascii \\d hits arabic    = " + ascii.matcher(arabic).find());
        System.out.println("ascii \\d hits fullwidth = " + ascii.matcher(fullwidth).find());

        // UNICODE_CHARACTER_CLASS 打开后 \d 跟随 Unicode 十进制数字
        Pattern unicode = Pattern.compile("\\d", Pattern.UNICODE_CHARACTER_CLASS);
        System.out.println("unicode \\d hits arabic    = " + unicode.matcher(arabic).find());
        System.out.println("unicode \\d hits fullwidth = " + unicode.matcher(fullwidth).find());
    }
}

Two notions of “digit” in one file

Character.isDigit covers every Unicode Nd (decimal digit) category, so it answers true for '3', for '\u0663' (Arabic-Indic), and for '\uFF11' (fullwidth). Regex \d is different: by default the predefined character classes are ASCII-only, so Pattern.compile("\d") matches none of the two non-ASCII samples. The third pattern recompiles with Pattern.UNICODE_CHARACTER_CLASS, which switches \d to the Unicode definition.

The seven-line comparison

isDigit ascii     = true
isDigit arabic    = true
isDigit fullwidth = true
ascii \d hits arabic    = false
ascii \d hits fullwidth = false
unicode \d hits arabic    = true
unicode \d hits fullwidth = true

The paired labels make the divergence readable at a glance: the same two strings flip from false to true between the plain and the flag-enabled matcher. Practical consequence, per the file’s own comments: validating digits with \d silently rejects international input unless the flag is set, while isDigit never needs it.

The line that changes the class’s scope

Pattern unicode = Pattern.compile("\d", Pattern.UNICODE_CHARACTER_CLASS);

The flag alters the whole family of predefined classes (\d, \w, \s, …), not just \d — one compile-time decision per Pattern.

Interactive Tools for This Topic

FAQ

What does Unicode Digit Classes IsDigit And Regex print when run?
Running the file directly is enough — expect labeled output lines such as `isDigit ascii =`, `isDigit arabic =`, `isDigit fullwidth =`.