如何检查字符串是否包含特定范围内的数字,例如java中的11到26:例如:
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");
}
}
答案 0 :(得分:4)
如果您的字符串只有一个数字,您可以使用正则表达式来查找它,解析它,并检查它是否在范围内:
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");
}
如果字符串中有多个数字以及检查其中是否有任何数字在范围内,请使用循环:
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;
}
}
你的方法应该返回一个布尔值,而不是打印结果:
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;
}
正如Anton Balaniuc建议的那样,你可以在Java 9中做到这一点:
return Pattern.compile("[-+]?\\d+").matcher(s).results()
.map(MatchResult::group)
.map(Integer::parseInt)
.anyMatch(n -> n >= 11 && n <= 26);