首页 > 解决方案 > 验证用户输入

问题描述

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

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

  1. 字符串必须至少有九个字符
  2. 字符串仅由字母和数字组成。
  3. 字符串必须至少包含两位数字。

标签: javaregexstringmethodspattern-matching

解决方案


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

  • ^: 在行首断言位置
  • 积极前瞻 (?=(?:\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])
      
  • 模式, [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

推荐阅读