user3649712
user3649712

Reputation: 23

How to check if the string contains numbers from a specific range, for eg from 11 to 26 in java

How to check if the string contains numbers from a specific range, for eg from 11 to 26 in java: For example:

public void checkStringForNumbers(){
    String str = "Green (Low): 20"
    if(String.valueOf(str).contains(numbers between 11 to 26)==true){
        System.out.println("I got 11 to 26 string");
    } else {
        System.out.println("I got a different value range");
    }
}

Upvotes: 0

Views: 92

Answers (1)

Sweeper
Sweeper

Reputation: 271175

If your string has only one number, you can use a regex to find it, parse it, and check if it is in range:

String s = "Green (Low): 20";
Matcher m = Pattern.compile("[-+]?\\d+").matcher(s);
if (m.find())
    int number = Integer.parseInt(m.group());
    if (number <= 26 && number >= 11) {
        System.out.println("Contains number between 11 and 26!");
    } else {
        System.out.println("Contains number but not between 11 and 26!");
    }
} else {
    System.out.println("Contains no numbers");
}

If you have multiple numbers in the string and what to check if any of them is in range, use a loop:

String s = "Green (Low): 20";
Matcher m = Pattern.compile("[-+]?\\d+").matcher(s);
while (m.find()) {
    int number = Integer.parseInt(m.group());
    if (number <= 26 && number >= 11) {
        System.out.println("Contains number between 11 and 26!");
        break;
    }
}

Your method should probably return a boolean instead of printing the result out:

static boolean hasNumberInRange(String s) {
    Matcher m = Pattern.compile("[-+]?\\d+").matcher(s);
    while (m.find()) {
        int number = Integer.parseInt(m.group());
        if (number <= 26 && number >= 11) {
            return true;
        }
    }
    return false;
}

As Anton Balaniuc suggested, you can do this in Java 9:

return Pattern.compile("[-+]?\\d+").matcher(s).results()
       .map(MatchResult::group)
       .map(Integer::parseInt)
       .anyMatch(n -> n >= 11 && n <= 26);

Upvotes: 4

Related Questions