2013-03-04 65 views
-3

我得到的錯誤在這條線:未閉合組14

Pattern pattern = Pattern.compile(word + "\\(.*\\)"); 

它說:

Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Unclosed group near index 14 

我知道,當你離開沒有逃過特殊字符這個錯誤,但我沒有看到任何有..

全碼:

   StyleConstants.setItalic(set, true); 
        for (String word : code.split("\\s")) { 
         Pattern pattern = Pattern.compile(word + "\\(.*\\)"); 
         Matcher matcher = pattern.matcher(word); 
         while (matcher.find()) { 
          doc.setCharacterAttributes(matcher.start(), word.length(), set, true); 
         } 
        } 

代碼是一個字符串。它爆炸代碼並檢查每個單詞。如果匹配單詞,顏色也

+0

什麼是word'的'價值 - 如果它有一個正則表達式其中的角色也必須逃脫。 – Dobbo 2013-03-04 18:02:08

+0

那麼,你現在在哪裏告訴我們「單詞」的內容? – stema 2013-03-04 18:03:48

+0

如何知道單詞的內容? Word是字符串代碼的一部分。如果字符串是「一些大字符串」,那麼循環將通過「一些」,「大」和「字符串」,並檢查每個。如果代碼將是「一些函數()」,那麼它應該通過「一些」和「功能()」 – user2102972 2013-03-04 18:05:18

回答

0

我試過如下:

Pattern pattern = Pattern.compile("abcd" + "\\(.*\\)"); 
log.debug("RegEx: " + pattern); 

這工作得很好:

RegEx: abcd\(.*\) 

我只能假設你有一些轉義字符word

如果你不知道的word在編譯時的值,那麼構建模式並調用compile()方法之前記錄它:

String regex = word + "\\(.*\\)"; 
System.out.println("Regex: \"" + regex + "\""); 
Pattern pattern = Pattern.compile(regex); 
+0

但是我怎麼能知道單詞是否包含一些未釋放的字符?我應該在編譯之前檢查每個單詞嗎?沒有其他選擇? – user2102972 2013-03-04 18:10:58

+0

是的,你必須在編譯之前掃描每個單詞。 'compile()'不知道什麼是和什麼是一個單詞 - 它將整個事物看作一個必須遵循正則表達式語法的正則表達式模式。 – Dobbo 2013-03-04 18:15:32