使用正则表达式验证密码

huangapple go评论69阅读模式
英文:

Using regex to validate password

问题

这是我的当前代码:

import java.util.*;
import java.util.regex.*;

public class TestClass {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String password = scan.nextLine();
        if (password.length() >= 10) {
            if (Pattern.matches("[a-zA-Z]\\d{2}", password)) {
                System.out.println("Password is valid");
            }
        }
    }
}

描述

密码规则:

  • 密码至少要有十个字符。
  • 密码只能由字母和数字组成。
  • 密码必须包含至少两个数字。

这是我一直在尝试用于验证密码的代码,但它没有打印出我的输出。

英文:

This is my current code:

import java.util.*;
import java.util.regex.*;

public class TestClass {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String password = scan.nextLine();
        if (password.length() >= 10) {
            if (Pattern.matches("[a-zA-Z]\\d{2}", password)) {
                System.out.println("Password is valid");
            }
        }
    }
}

Description

Password rules:

  • A password must have at least ten characters.
  • A password consists of only letters and digits.
  • A password must contain at least two digits

This is the code that I've been trying for validating the password but It doesn't print my output.

答案1

得分: 1

我会使用以下正则表达式模式来满足您的要求:

^(?!.*[^A-Za-z0-9])(?=.{10,}).*\d.*\d.*$

这个模式表示:

  • ^:从密码的开头开始
  • (?!.*[^A-Za-z0-9]):向前查找并断言我们不会看到任何非字母或数字字符
  • (?=.{10,}):向前查找并断言密码长度为10或更长
  • .*\d.*\d.*:然后匹配任何模式,只要有两个数字出现
  • $:密码的结尾

我可能会直接在这里使用 String#matches

Scanner scan = new Scanner(System.in);
String password = scan.nextLine();
if (password.matches("(?!.*[^A-Za-z0-9])(?=.{10,}).*\\d.*\\d.*")) {
    System.out.println("密码有效");
}

请注意,当与 String#matches 一起使用该正则表达式模式时,我们会从模式中删除 ^$ 锚定符,因为该方法会隐式地将模式应用于整个字符串输入。

英文:

I would use the following regex pattern to assert your requirements:

^(?!.*[^A-Za-z0-9])(?=.{10,}).*\\d.*\\d.*$

This pattern says to:

^                   from the start of the password
(?!.*[^A-Za-z0-9])  look ahead and assert that we do NOT see any non letters or digits
(?=.{10,})          look ahead and assert that password length be 10 or longer
.*\\d.*\\d.*        then match any pattern so long as two digits be present
$                   end of the password

I would probably just directly use String#matches here:

Scanner scan = new Scanner(System.in);
String password = scan.nextLine();
if (password.matches("(?!.*[^A-Za-z0-9])(?=.{10,}).*\\d.*\\d.*")) {
    System.out.println("Password is valid");
}

Note that we drop the ^ and $ anchors from the regex pattern when using it with String#matches because this method implicitly applies the pattern to the entire string input.

huangapple
  • 本文由 发表于 2020年10月9日 10:55:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/64273303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定