How to check if a character is alphanumeric in Rust

Overview

With the is_alphanumeric() method, we can check if a character is alphanumeric in Rust. Characters that are said to be alphanumeric, are comprise of the twenty-six alphabets and the numbers 0 to 9.

Characters that are not alphanumeric include punctuation characters like the comma,,, and some mathematical characters like the plus sign, +.

Syntax

character.is_alphanumeric()
Syntax to call the alphanumeric() method

Parameters

This method takes the parameter, character, to check if it is alphanumeric.

Return value

A boolean value is returned. If the character is alphanumeric, then a true is returned. Otherwise, false is returned.

Example

fn main(){
// initialise some characters
let char1 = 'E';
let char2 = '+';
let char3 = '=';
let char4 = '3';
let char5 = '!';
// check if characters are alphanumeric
println!("{}", char1.is_alphanumeric());
println!("{}", char2.is_alphanumeric());
println!("{}", char3.is_alphanumeric());
println!("{}", char4.is_alphanumeric());
println!("{}", char5.is_alphanumeric());
}

Explanation

In the code above,

  • Lines 3–7: We initialize some characters. Some of which are alphanumeric and some of which are not.
  • Lines 10–14: We check if the characters are alphanumeric using the is_alphanumeric() method. Then we print the result to the console.

Free Resources