2013-05-21 72 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

嗯,不,我們都。 –

相關問題