验证用户输入

validate a user input

你好,我是编程新手,我在理解我的作业时遇到了问题。我知道这对你们来说可能是一个非常简单的问题,对此我深表歉意。有没有可能她只是要我写一个方法来执行给定的指令?

编写一个程序,根据说明判断用户输入是否有效。**

  1. 一个字符串必须至少有九个字符
  2. 一个字符串只包含字母和数字。
  3. 字符串必须至少包含两位数字。

要求 #1:一个字符串必须至少有九个字符

这个通过检查String的长度是否大于9来解决,用s.length()>9

要求 #2:字符串仅由字母和数字(整数)组成。

使用正则表达式 [a-zA-Z0-9]+,它匹配所有拉丁字母字符和数字。

要求 #3:字符串必须至少包含两位数字。

我写了一个循环遍历每个字符并使用 Character.isDigit() 来检查它是否是数字的方法。

查看:

public static boolean verify(String s) {
    final String regex = "[a-zA-Z0-9]+";
    System.out.println(numOfDigits(s));
    return s.length() > 9 && s.matches(regex) && numOfDigits(s) > 2;
}

public static int numOfDigits(String s) {
    int a = 0;
    int b = s.length();
    for (int i = 0; i < b; i++) {
        a += (Character.isDigit(s.charAt(i)) ? 1 : 0);
    }
    return a;
}

您可以简单地使用正则表达式,^(?=(?:\D*\d){2})[a-zA-Z\d]{9,}$,其解释如下:

  • ^ : 断言行首的位置
  • Positive Lookahead (?=(?:\D*\d){2})
    • 非捕获组(?:\D*\d){2}
      {2} matches the previous token exactly 2 times
      \D matches any character that's not a digit (equivalent to [^0-9])
      * matches the previous token between zero or more time (greedy)
      \d matches a digit (equivalent to [0-9])
      
  • pattern[a-zA-Z\d]{9,}
    {9,} matches the previous token between 9+ times (greedy)
    a-z matches a single character in a-z
    A-Z matches a single character in A-Z
    \d matches a digit (equivalent to [0-9])
    
  • $ : 断言行尾的位置

演示:

import java.util.stream.Stream;

public class Main {
    public static void main(String args[]) {
        //Test
        Stream.of(
                    "helloworld",
                    "hello",
                    "hello12world",
                    "12helloworld",
                    "helloworld12",
                    "123456789",
                    "hello1234",
                    "1234hello",
                    "12345hello",
                    "hello12345"
        ).forEach(s -> System.out.println(s + " => " + isValid(s)));
    }
    static boolean isValid(String s) {
        return s.matches("^(?=(?:\D*\d){2})[a-zA-Z\d]{9,}$");
    }
}

输出:

helloworld => false
hello => false
hello12world => true
12helloworld => true
helloworld12 => true
123456789 => true
hello1234 => true
1234hello => true
12345hello => true
hello12345 => true