如何检查字符串是否包含 3 位或更多数字

我目前正在尝试检查字符串是否包含 3 位或更多数字。如果是的话,那么它是有效的。我该如何修复它?


System.out.print("Enter a string: ");  //111Hello <-- valid

String word = input.nextLine();

boolean numbers = word.matches(".*\\d{3,}"); 

System.out.println(numbers);

输出:


Invalid


这里有些例子:


输入: Hello244


输出: Valid


输入: 3Hello


输出: Invalid


输入: 6Hello2Hello5


输出: Valid


慕尼黑8549860
浏览 74回答 4
4回答

慕村9548890

使用正则表达式很容易做到这一点,因为包含至少三个数字的字符串集是正则语言- 正是正则表达式旨在识别的语言。public boolean hasThreeDigits(String s) {     return s.matches(".*\\d.*\\d.*\\d.*"); }正则表达式.*\d.*\d.*\d.*将三个数字与其之前、之后或之间的任何内容相匹配。

回首忆惘然

为什么不使用计数器并循环每个字符,然后测试它是否是数字?这是伪代码:System.out.print("Enter a string: ");&nbsp; //111Hello <-- validString word = input.nextLine();int numberOfDigits = countDigits(word, 3);if (numberOfDigits) >= 3{//...int countDigits(String val, int max){&nbsp; &nbsp; int cnt = 0;&nbsp; &nbsp; for(int i =0; i < val.length(); i++){&nbsp; &nbsp; &nbsp; &nbsp; char c = val.charAt(i);&nbsp; &nbsp; &nbsp; &nbsp; if(Character.isDigit(c){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cnt++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if(cnt == max)return;&nbsp; &nbsp; }&nbsp; &nbsp; return cnt;}https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isDigit(char)

LEATH

让我们用正则表达式来做到这一点。这似乎并不是真正需要的,但我们假设这是一个作业:import java.util.regex.Matcher;import java.util.regex.Pattern;public class FindDigits {&nbsp; &nbsp; public static final Pattern DIGIT_PATTERN = Pattern.compile("\\p{Digit}");&nbsp; &nbsp; private static int countDigits(String input) {&nbsp; &nbsp; &nbsp; &nbsp; final Matcher m = DIGIT_PATTERN.matcher(input);&nbsp; &nbsp; &nbsp; &nbsp; int c = 0;&nbsp; &nbsp; &nbsp; &nbsp; while (m.find()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return c;&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < args.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; final int c = countDigits(args[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("Input : \"%s\"%nOutput: %s%n", args[i], c >= 3 ? "Valid" : "Invalid");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}该答案假设输入是命令行上的一组字符串。它定义了一个函数来计算由单个数字组成的模式的出现次数。当然也可以到3就停止计数。我主要发布这个,因为Matcher.find它经常被忽视,因为它没有在String. 它通常使阅读正则表达式变得更加容易,因为您不需要定义您不需要的内容。否则,您将陷入正则表达式字符串之类的困境,".*\\d.*\\d.*\\d.*"这些字符串有点可怕并且无法很好地扩展。除了 while 循环之外,您还可以m.results().count()在更高版本的 Java 运行时上使用。在这种情况下,一句台词将是:long count = Pattern.compile("\\p{Digit}").matcher(input).results().count();

忽然笑

也许不是最优雅的解决方案,但非常简短明了:System.out.println(input.replaceAll("\\D","").length()&nbsp;>&nbsp;2);我最喜欢kaya3的解决方案
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java