java - 验证用户输入
问题描述
您好,我是编程新手,无法理解我的任务。我知道这对你们来说可能是一个非常简单的问题,对此我深表歉意。有没有可能她只是要我写一个方法来执行给定的指令?
编写一个程序,根据指令判断用户输入是否有效。**
- 字符串必须至少有九个字符
- 字符串仅由字母和数字组成。
- 字符串必须至少包含两位数字。
解决方案
您可以简单地使用正则表达式,^(?=(?:\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
推荐阅读
- kubernetes - 为什么我的永久性磁盘无法挂载到我的 pod?
- java - 如何在列表中计算相似的id对象并在recyclerview中显示?
- aws-api-gateway - 通过无服务器框架为 AWS API Gateway 设置响应模型
- c# - 在 TextBlock 的 ObservableCollection 中,是否可以通过编程方式选择 TexBlock 中的文本?
- python - 对嵌套字典列表进行排序
- http - 错误请求:使用 curl 时缺少请求正文
- python - 如何忽略 pandas.to_numeric() 中的错误并将 str 更改为 int
- python - 在python中读取单元格值
- python - 通过 Python3 读写 YAML 文件
- c# - C# 将 3D 矩阵展平/扩展为锯齿状数组