简体   繁体   English

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

[英]How to check if a String contains 3 digits or more

I'm currently trying to check if a string contains 3 digits or more.我目前正在尝试检查字符串是否包含 3 位或更多位。 If it does, then it is valid.如果是,那么它是有效的。 How can I fix it?我该如何解决?

System.out.print("Enter a string: ");  //111Hello <-- valid
String word = input.nextLine();
boolean numbers = word.matches(".*\\d{3,}"); 
System.out.println(numbers);

Output: Output:

Invalid

Here are some examples:这里有些例子:

Input: Hello244输入: Hello244

Output: Valid Output: Valid

Input: 3Hello输入: 3Hello

Output: Invalid Output: Invalid

Input: 6Hello2Hello5输入: 6Hello2Hello5

Output: Valid Output: Valid

This is easy to do using a regular expression, because the set of strings containing at least three digits is a regular language - precisely what regular expressions are designed to recognise.使用正则表达式很容易做到这一点,因为包含至少三位数字的字符串集是一种正则语言- 正是正则表达式旨在识别的内容。

public boolean hasThreeDigits(String s) {
    return s.matches(".*\\d.*\\d.*\\d.*");
}

The regex .*\d.*\d.*\d.* matches three digits with anything before, after or in between.正则表达式.*\d.*\d.*\d.*将三位数字与之前、之后或之间的任何内容匹配。

Why not have a counter and loop over each character and then test if its a digit?为什么不设置一个计数器并遍历每个字符,然后测试它是否为数字?

This is pseudo code:这是伪代码:

System.out.print("Enter a string: ");  //111Hello <-- valid
String word = input.nextLine();
int numberOfDigits = countDigits(word, 3);
if (numberOfDigits) >= 3{//...

int countDigits(String val, int max){
    int cnt = 0;
    for(int i =0; i < val.length(); i++){
        char c = val.charAt(i);
        if(Character.isDigit(c){
            cnt++;
        }
        if(cnt == max)return;
    }
    return cnt;
}

https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isDigit(char) https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isDigit(char)

Let's do this with regular expressions.让我们用正则表达式来做这件事。 That doesn't really seem required, but let's assume this is an assignment:这似乎不是必需的,但让我们假设这是一个作业:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FindDigits {
    public static final Pattern DIGIT_PATTERN = Pattern.compile("\\p{Digit}");

    private static int countDigits(String input) {
        final Matcher m = DIGIT_PATTERN.matcher(input);
        int c = 0;
        while (m.find()) {
            c++;
        }
        return c;
    }

    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            final int c = countDigits(args[i]);
            System.out.printf("Input : \"%s\"%nOutput: %s%n", args[i], c >= 3 ? "Valid" : "Invalid");
        }
    }
}

This answer assumes that the input is a set of strings on the command line.这个答案假设输入是命令行上的一组字符串。 It defines a function to count the occurrences of pattern consisting of a single digit.它定义了一个 function 来计算由单个数字组成的模式的出现次数。 It could of course stop counting at 3.它当然可以在 3 时停止计数。

I'm mainly posting this because Matcher.find is often overlooked as it doesn't have a convenience method defined in String .我主要发布这个是因为Matcher.find经常被忽视,因为它没有在String中定义的便利方法。 It often makes for much easier to read regular expressions as you don't need to define what you are not looking for.它通常使阅读正则表达式变得更加容易,因为您不需要定义您不需要的内容。 Otherwise you're stuck with regular expressions strings such as ".*\\d.*\\d.*\\d.*" which are kind of horrible and do not scale well.否则你会被正则表达式字符串困住,例如".*\\d.*\\d.*\\d.*"这有点可怕并且不能很好地扩展。


Instead of the while loop you can also use m.results().count() on a later version of the Java runtime.除了 while 循环,您还可以在 Java 运行时的更高版本上使用m.results().count() In that case a one-liner would be:在这种情况下,单线将是:

long count = Pattern.compile("\\p{Digit}").matcher(input).results().count();

Maybe not the most elegant solution, but pretty short and straightforward:也许不是最优雅的解决方案,但非常简短明了:

System.out.println(input.replaceAll("\\D","").length() > 2);

I prefer kaya3's solution the most我最喜欢kaya3的解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查字符串是否仅包含 Java 中的数字 - How to check if a string contains only digits in Java 如何检查字符串只包含数字和小数点? - How to check a string contains only digits and decimal points? 如何检查字符串只包含数字和一个小数点? - How to check a string contains only digits and one occurrence of a decimal point? 检查字符串数字数组是否包含符号 - Check if String array of digits contains symbol 检查字符串是否仅包含数字且使用REGEX的数字是否相同? - Check if a String only contains digits and the digits are not the same using REGEX? 如何检查包含多个模式的字符串并替换该模式 - How to check a string that contains more than one pattern and replace that pattern 如何在Java中使用正则表达式检查字符串是否包含两个字母和数量可变的数字? - How to check with a regex if a String contains two letters and a variable amount of digits in Java? 正则表达式检查字符串是否仅包含数字不起作用 - Regex check if a string contains only digits doesn't work 使用正则表达式检查 int/string 是否包含特定数字 - check a int/string contains specific digits in it using regex 用于检查字符串是否仅包含数字和运算符(但没有 2 个连续运算符)的正则表达式 - Regex expression to check if a string only contains digits and operators (but no 2 consecutive operators)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM