24

What is the idiomatic way in Rust to check if a string only contains a certain set of characters?

Aart Stuurman
  • 3,188
  • 4
  • 26
  • 44

2 Answers2

37

You'd use all to check that all characters are alphanumeric.

fn main() {
    let name = String::from("Böb");
    println!("{}", name.chars().all(char::is_alphanumeric));
}
  • chars returns an iterator of characters.
  • all returns true if the function is true for all elements of the iterator.
  • is_alphanumeric checks if its alphanumeric.

For arbitrary character sets you can pass whatever function or code block you like to all.

Interestingly, the corresponding methods on str were explicitly removed for subtle Unicode reasons.

Schwern
  • 153,029
  • 25
  • 195
  • 336
8

There is is_alphanumeric():

fn main() {
    println!("{}", "abcd".chars().all(|x| x.is_alphanumeric()));
}
Stargateur
  • 24,473
  • 8
  • 65
  • 91