Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Regex into Rust regex

I have a Javascript regex for password validation:

// Validates password with
// — No white spaces
// — At least one upper case English letter, (?=.*?[A-Z])
// — At least one lower case English letter, (?=.*?[a-z])
// — At least one digit, (?=.*?[0-9])
// — Minimum eight in length .{8,} (with the anchors)

const passwordRegex = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{6,10}$/;

I am trying to translate it into Rust regex using regex library; but it seems that it doesn’t support lookahead: https://docs.rs/regex/latest/regex/

use regex::Regex;

pub fn validate_password(string: &str) -> bool {
  let regex_no_whitespaces = Regex::new(r"^\s*\S+\s*$").unwrap();
  let regex_password = Regex::new(r"^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{6,10}$").unwrap();
  let password_valid = regex_password.is_match(&string);
  let password_has_no_whitespaces = regex_no_whitespaces.is_match(&string);
  let is_valid = password_valid && password_has_no_whitespaces;

  return is_valid;
}

What is the common way to validate a string with multiple conditions without a lookahead?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT: it is possible to do it using Regex, here a version in the playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c6f69f5018e38677af1624a7bfcd186c. But the version provided by @sirdarius is way cleaner.

>Solution :

Here is a solution that does not use regular expressions.

fn is_password_valid(s: &str) -> bool {
    let mut has_whitespace = false;
    let mut has_upper = false;
    let mut has_lower = false;
    let mut has_digit = false;

    for c in s.chars() {
        has_whitespace |= c.is_whitespace();
        has_lower |= c.is_lowercase();
        has_upper |= c.is_uppercase();
        has_digit |= c.is_digit(10);
    }

    !has_whitespace && has_upper && has_lower && has_digit && s.len() >= 8
}

Playground link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading