如何判断字符串中是否有未知数字?

时间:2013-05-21 18:36:02

标签: java string

我有一个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."));

怎么做?

4 个答案:

答案 0 :(得分:5)

使用regular expression

if(thestring.matches("^I, am awesome. And I'm \\d+ years old$")) {
    //Do stuff
}

答案 1 :(得分:2)

答案 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]]   

还有 - Lesson: Regular Expressions

Pattern class is good study too