2014-05-08 57 views
0

我試圖創建一個匹配器實例來將字符串拉出字符串。這是我用的:Java的匹配器不能正確匹配輸入

Matcher base = Pattern.compile("red|green|blue|\\+|\\(|\\)").matcher(input.trim()); 
    while (!base.hitEnd()) { 
     if (base.find()) { 
      String s = base.group(); 
      output += String.format(" %s", s); 
     } 
     else { 
      throw new IllegalArgumentException("Invalid tokens in the input! " + base.toString()); 
     } 
    } 

在這種情況下input是我的輸入字符串被標記。然而,即使我給它輸入"red",它仍會拋出異常,並顯示該對象嘗試不匹配(沒有更改正在考慮的索引,沒有先前的匹配)。

我的目標是匹配確切詞"red", "green", "blue",加號和開始和結束的parens,作爲標記。我錯過了什麼?

回答

1

如果我理解正確,你想拋出你的異常,當你找不到任何令牌。如果輸入字符串不包含任何標記,則您對該標記進行的這種修改將正確地找到您正在查找的標記並引發異常。

Matcher base = Pattern.compile("\\bred\\b|\\bgreen\\b|\\bblue\\b|[+()]{1}").matcher(input.trim()); 
while (!base.hitEnd()) { 
    if (base.find()) { 
     String s = base.group(); 
     System.out.println("Found: " + s); 
     output += String.format(" %s", s); 
    } 
} 
if (output.isEmpty()) { 
    throw new IllegalArgumentException("Invalid input no matching tokens found! " + base.toString()); 
} 

我更新了你的正則表達式中的一些東西。我在red, green, blue周圍添加了\\b的單詞邊界,並且我將+()組合爲一個字符組。字符組將完全匹配[]中任何字符的1。