create a password with symbols in rust

To create a password with symbols in Rust, we can use the rand crate to generate a random string and the regex crate to check if the generated string contains symbols.

Here's an example code that generates a random string with a length of 10 containing symbols:

main.rs
extern crate rand;
extern crate regex;

use rand::Rng;
use regex::Regex;

fn generate_password_with_symbol() -> String {
    let mut rng = rand::thread_rng();
    let password: String = rng.sample_iter(&rand::distributions::Alphanumeric)
        .take(10)
        .map(char::from)
        .collect();
    let re = Regex::new(r"[!@#$%^&*_+-=()|{}\[\],.?/:;]").unwrap();

    if re.is_match(&password) {
        return password;
    } else {
        return generate_password_with_symbol();
    }
}

fn main() {
    let password = generate_password_with_symbol();
    println!("{}", password);
}
593 chars
26 lines

In this code, we use the sample_iter method to generate a random string of length 10 containing alphanumeric characters. We then use the Regex crate to check if the generated string contains any of the symbols we want to use in our password.

If the generated string contains at least one symbol, we return it as the password. If not, we recursively call the generate_password_with_symbol function until we get a password containing at least one symbol.

gistlibby LogSnag