What is the idiomatic way in Rust to check if a string only contains a certain set of characters?
Asked
Active
Viewed 2.0k times
2 Answers
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
-
8`s.chars().all(char::is_alphanumeric)` also works in this case. – Shepmaster Jul 17 '18 at 23:51
-
1And for clarity, the "generic" version is to change the predicate in `all`. – Shepmaster Jul 17 '18 at 23:51