简体   繁体   中英

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. 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:

Invalid

Here are some examples:

Input: Hello244

Output: Valid

Input: 3Hello

Output: Invalid

Input: 6Hello2Hello5

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.

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)

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. It could of course stop counting at 3.

I'm mainly posting this because Matcher.find is often overlooked as it doesn't have a convenience method defined in 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.


Instead of the while loop you can also use m.results().count() on a later version of the Java runtime. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM