Unicode Char Classes Beyond ASCII

Validate text with Unicode-aware predicates: is_alphabetic accepts é and 名, is_numeric accepts Arabic digits, and control characters are rejected.

RustForm Validation

Code

rustsnippet
28 lines
// Unicode 字符类别 char classes:ASCII 工具看不见的字母在这里都算字母
fn valid_display_name(name: &str) -> bool {
    !name.is_empty()
        && name.chars().all(|c| c.is_alphanumeric() || c == ' ')
        && !name.chars().any(|c| c.is_control())
}

// 账号编码只允许 ASCII 数字
fn valid_account_code(code: &str) -> bool {
    !code.is_empty() && code.chars().all(|c| c.is_ascii_digit())
}

fn main() {
    for c in ['ñ', '名', '٣', 'Ω', ' ', '7', '\n'] {
        println!(
            "{c:?}: alphabetic={} numeric={} control={} whitespace={}",
            c.is_alphabetic(),
            c.is_numeric(),
            c.is_control(),
            c.is_whitespace(),
        );
    }

    println!("name ok: {}", valid_display_name("josé garcía"));
    println!("name declined: {}", valid_display_name("bad\u{7f}name"));
    println!("code ok: {}", valid_account_code("0042"));
    println!("code declined: {}", valid_account_code("12a4"));
}

How this snippet works

The code’s whole job belongs to the functions valid_display_name, valid_account_code and main.

The cycling part of this snippet is for c in ['ñ', '名', '٣', 'Ω', ' ', '7', '\n'].

Points of care

  • Standard library end to end — paste it in and it runs.

Using it

Signature: fn valid_display_name(name: &str) -> bool

The run emits 4 labeled sections — name ok:, name declined:, code ok:, code declined: — one per step.

Treat main as the orchestrator calling valid_display_name and valid_account_code in a fixed order.

Key statements

fn valid_display_name(name: &str) -> bool {
    !name.is_empty()
        && name.chars().all(|c| c.is_alphanumeric() || c == ' ')
        && !name.chars().any(|c| c.is_control())
}
fn valid_account_code(code: &str) -> bool {
    !code.is_empty() && code.chars().all(|c| c.is_ascii_digit())
}

Interactive Tools for This Topic

FAQ

What does Unicode Char Classes Beyond ASCII print when run?
Run it as a complete program — the output lines carry labels such as `name ok:`, `name declined:`, `code ok:`.