gpt4 book ai didi

java - 使用 RegEx 验证输入是否包含 a-Z 中的多个字符

转载 作者:太空宇宙 更新时间:2023-11-04 11:27:52 25 4
gpt4 key购买 nike

我正在尝试使用 RegEx 验证输入是否包含从 a-Z 的多个字符。

它可以包含任意数量的字符、空格,但可以/不可以包含 a-Z 中的一个字母。

如果包含,则不会超过一个。

public class HelloWorld {

public static void main(String []args){

String s = "333444434";//None / Only 1
//String s = "A b c";//More than 1
//String s = "111 1Aa1 1111";//More than 1
//String s = "98X8 8A+----!";//More than 1
//String s = "98A88a+----!";//More than 1
//String s = "c+->18888882";//None / Only 1
//String s = "1c+-**>18888882";//None / Only 1

if(s.matches("([a-zA-Z]){0,1}")){
System.out.println("None / Only 1");
}else{
System.out.println("More than 1");
}
}
}

最佳答案

使用匹配器搜索 [a-zA-Z] 正则表达式并对其进行计数:

Matcher matcher = Pattern.compile("[a-zA-Z]")
.matcher(s);
int counter = 0;
while (matcher.find()) {
counter++;
}
if (counter <= 1) {
System.out.println("None / Only 1");
} else {
System.out.println("More than 1");
}

关于java - 使用 RegEx 验证输入是否包含 a-Z 中的多个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44153355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com