我有一个if
语句,用于检查变量是否等于某个字符串。但是,我想检查字符串中是否还有一个数字。像这样:
if(thestring.equals("I, am awesome. And I'm " + Somehowgetifthereisanumberhere + " years old")) {
//Do stuff
}
或者更具体地说, x 是未知数字,只知道那里有一个数字(任意数字):
String str = item.substring(item.indexOf("AaAaA" + x), item.lastIndexOf("I'm cool."));
怎么做?
答案 0 :(得分:5)
if(thestring.matches("^I, am awesome. And I'm \\d+ years old$")) {
//Do stuff
}
答案 1 :(得分:2)
您可以使用正则表达式。
Pattern pattern = Pattern.compile(".*[^0-9].*");
参考文献:
答案 2 :(得分:2)
这个正则表达式应该在任何字符串中找到任何一个,两个或三个数字(如果它们是102岁):
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestClass {
public static void main(String[] args) {
Pattern p = Pattern.compile("\\d\\d?\\d?");
Matcher m = p.matcher("some string with a number like this 536 in it");
while(m.find()){
System.out.println(m.group()); //This will print the age in your string
System.out.println(m.start()); //This will print the position in the string where it starts
}
}
}
或者这个来测试整个字符串:
Pattern p = Pattern.compile("I, am awesome. And I'm \\d{1,3} years old"); //I've stolen Michael's \\d{1,3} bit here, 'cos it rocks.
Matcher m = p.matcher("I, am awesome. And I'm 65 years old");
while(m.find()){
System.out.println(m.group());
System.out.println(m.start());
}
答案 3 :(得分:1)
您想要使用正则表达式。见 - Using Regular Expressions to Extract a Value in Java
匹配字母'd','e'或'f',例如:
[a-z&&[def]]