2013-10-10 29 views
0

我試圖去掌握正則表達式的語法。有誰知道我可以做以下工作嗎?在一個正則表達式小數位上的Java匹配

// if there is already a decimal place in the string ignore 
    String origString = txtDisplay.getText(); 

    Pattern pattern = Pattern.compile("/\\./"); 

    //pattern = 
    if(pattern.matcher(origString)){ 
     System.out.println("DEBUG - HAS A DECIMAL IGNORE"); 
    } 
    else{ 
     System.out.println("DEBUG - No Decimal"); 
    } 
+0

感謝您的意見。我會繼續嘗試。我是新來的Java所以即時通訊嘗試學習如何做到這一點。 –

回答

1

Java正則表達式不需要模式分隔符;即它們在模式的開始和結束時不需要//斜槓,或者它們將按字面解釋。

您需要將您的模式更改爲:

\\. 

,然後你可以,你可以檢查是否有匹配這樣的:

Matcher matcher = pattern.marcher(origString); 
if(matcher.find()){ 
    System.out.println("DEBUG - HAS A DECIMAL IGNORE"); 
} 
else{ 
    System.out.println("DEBUG - No Decimal"); 
} 

,但如果你想檢查是否字符串包含一個圓點或其他任何字符串文字你可以使用:

bool doesItContain = origString.indexOf('.') != -1; 

其中indexOf()起飛s作爲任何字符串的參數。

+0

它不創建Matcher對象。我的IDE強調它是紅色的說不能找到符號?任何想法是什麼意思?我需要輸入什麼東西才能起作用? –

+1

@Robbo_UK啊是的。你需要導入'import java.util.regex。*'; –