2013-05-21 73 views
0

我有一个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

只需使用正则表达式。 – BackSlash

+0

看着我..我认为这已被问:http://stackoverflow.com/questions/372148/regex-to-find-an-integer-within-a-string –

回答

5

使用regular expression

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

另外请注意,双反斜杠是因为双反斜杠\\转换为字符串中的单个反斜杠,然后序列\ d被正则表达式引擎查看并解析。 –

+0

这真棒,但我可以以某种方式把这个在我的子串的东西?真的非常感谢你的帮助:) – GuiceU

+0

@GuiceU你没有;这将取代你的'thestring.equals()'调用。 –

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()); 
} 
+1

尝试'\\ d {1,3}'。 –

+0

迈克尔 - 甜!没有意识到你可以做到这一点。我仍然有训练轮子。大声笑:-) –

+0

嗯,不,我们都。 –

相关问题