2013-08-24 49 views
0

有一個字符串「12.2A12W99.0Z0.123Q9」 我需要找到3組:(double或int)(nondigit)(double或int) 所以在樣本的情況下,我希望這種情況發生:
matcher.group(1)= 「12.2」
matcher.group(2)= 「A」
matcher.group(3)= 「12」整數或雙正則表達式

我當前正則表達式只有匹配整數:「^(\ d +)(\ D)(\ d +)」 因此,我期待將組(\ d +)更改爲匹配整數或雙打的內容。

我完全不理解正則表達式,所以像我5這樣解釋會很酷。

+3

在網上搜索時,返回的第一個條目:[匹配浮點數用正則表達式(http://www.regular-expressions.info/floatingpoint.html),並回答您的問題 –

回答

1

請嘗試以下代碼: - 您的正則表達式僅與數字字符匹配。也要匹配小數點,您將需要:

Pattern.compile("\\d+\\.\\d+") 

private Pattern p = Pattern.compile("\\d+(\\.\\d+)?"); 

The。會被轉義,因爲這會在未轉義時匹配任何字符。

注意:這樣只會匹配帶小數點的數字,這就是您在示例中所使用的數字。

private Pattern p = Pattern.compile("\\d+(\\.\\d+)?"); 

public void testInteger() { 
    Matcher m =p.matcher("10"); 

    assertTrue(m.find()); 
    assertEquals("10", m.group()); 
} 

public void testDecimal() { 
    Matcher m =p.matcher("10.99"); 

    assertTrue(m.find()); 
    assertEquals("10.99", m.group()); 
} 
+2

什麼是':-'?我不能這樣旋轉我的嘴巴。 –

+0

非常感謝你這樣做,但我希望它能夠對付整數和雙打,而不僅僅是雙打。有沒有辦法寫一個正則表達式來做到這一點? – zvory

+0

剛纔我編輯的答案,讓我知道您的反饋 –