create a password with at least one symbol in rust

To create a password with at least one symbol in Rust, you can use regex to check if the password contains at least one symbol, and string manipulation to generate a random password.

Here's an example implementation:

main.rs
use rand::Rng;
use regex::Regex;

fn main() {
    let password = generate_password_with_symbol(8);
    println!("Random password with symbol: {}", password);
}

fn generate_password_with_symbol(length: usize) -> String {
    let symbol_regex = Regex::new(r"[!@#$%^&*()_+\-=\[\]{};':\"\\|,.<>\/?]").unwrap();

    loop {
        // Generate random password
        let password: String = rand::thread_rng()
            .sample_iter(&rand::distributions::Alphanumeric)
            .take(length)
            .map(char::from)
            .collect();

        // Check if password contains symbol
        if symbol_regex.is_match(&password) {
            return password;
        }
    }
}
685 chars
26 lines

In this implementation, we first define a regex pattern that matches common symbols. We then generate random passwords of a given length using rand::thread_rng(), and check if the generated password matches our regex pattern using symbol_regex.is_match(&password). If the password matches the pattern, we return the password. If not, we continue generating new passwords until we find one that contains a symbol.

gistlibby LogSnag