2012-08-29 71 views
0

我得到了一些動態更改的文本,我需要一種方法來查找其中的某些部分。 特別是像這樣的:在java中的正則表達式?我被卡住了

+ 124now

+ 78now

+ 45now

所以我的值總是以 「+」 加號開始,然後一些數字,最小的一個,然後在「現在「字。

我嘗試過很多辦法是這樣的:

if(myString.contains("+[0-9]+now")) //false 

,但我厭倦了......你能幫助嗎?

+4

'str.matches( 「\\ \\ + + d現在」)'' –

+7

#字符串需要contains'一個字符串作爲參數,不是一個正則表達式。 – assylias

回答

6

試試這個......

Pattern pat = Pattern.compile("\\+\\d+now"); 
Matcher mat = pat.matcher("Input_Text"); 

while(mat.find()){ 

    // Do whatever you want to do with the data now... 

} 
+0

+1順便說一句,得到匹配部分使用'mat.group()' – Pshemo

+0

y .....多數民衆贊成.... mat.group()或mat.group(0)都會在這裏做... ....我只需將其留給OP –

+0

true mat.group()返回mat.group(0):) – Pshemo

9

使用String#matches()代替:

if (myString.matches(".*\\+[0-9]+now.*")) 

此外,+是一種特殊的正則表達式字符,這就是爲什麼你需要逃避它。

如果需要捕獲號碼,使用PatternMatcher

Pattern p = Pattern.compile("\\+([0-9]+)now"); 
Matcher m = p.matcher(myString); 
while (m.find()) { 
    System.out.println(m.group(1)); 
} 

()是捕獲組,這意味着它會告訴正則表達式引擎匹配的內容,讓你可以稍後用group()來檢索它。

+0

OP詢問有關字符串的一部分,而不是整個字符串 – Qnan

3

你需要逃避的第一個「+」是這樣的:

if(myString.matches("\\+[0-9]+now")); 

的+意味着「從字面上找到+字符串」,而不是「發現該字符1次或多次」

+1

'String#contains'將字符串作爲參數,而不是正則表達式。 – assylias

1

contains不解釋其作爲正規表達式參數的方法。改爲使用方法matches。你必須逃離+爲好,像這樣:

if (myString.matches("\\+\\d+now")) 
2

我假設你想要麼匹配字符串或者也許提取中間的數字?在YOUT情況下,問題是,我們+特殊字符,因此你需要逃避它,像這樣:\\+,讓你的正則表達式變得\\+[0-9]+now

至於你的第二個問題,.contains方法需要一個字符串,而不是一個正則表達式,那麼你的代碼將無法正常工作。

String str = "+124now"; 
    Pattern p = Pattern.compile("\\+(\\d+)now"); 
    Matcher m = p.matcher(str); 

    while (m.find()) 
    { 
     System.out.println(m.group(1));   
    } 

在這種情況下,我已經提取數字以防萬一這是你之後的事情。

1

既然你說的串總是+開始,始終與now結束,爲什麼不檢查,這是真的。如果沒有,那麼有什麼不對。

String[] vals = {"+124now", "+78now", "-124now", "+124new"}; 

    for (String s : vals) { 
     if (s.matches("^\\+(\\d+)now$")) { 
      System.out.println(s + " matches."); 
     } else { 
      System.out.println(s + " does not match."); 
     } 
    } 

當然,如果你想捕獲的數字,然後使用像npinti建議的匹配。

編輯: 以下是如何獲得數量:

Pattern p = Pattern.compile("^\\+(\\d+)now$"); 
    for (String s : vals) { 
     Matcher m = p.matcher(s); 
     if (m.matches()) { 
      System.out.println(s + " matches and the number is: " + m.group(1)); 
     } else { 
      System.out.println(s + " does not match."); 
     } 
    }