2012-07-30 36 views
0

看看下面的代碼:更換所有方法拋出PatternSyntaxException

String comment = "1)FCR pick up in Hong Kong2)Local charges will be paiy in Hong Kong & in HK$.3)Booking:[email protected])FCR&DOC:[email protected]:00852-23021977Fax:00852-2730217Transaction865320submittedVirginiaWong(T1281954U005) and Status is INCMP on 10-JUN-11 11.28.45.764386 PM -05:00"; 
     //comment = comment.replaceAll("\\)", "\\\\)"); 
     //comment = comment.replaceAll("\\(", "\\\\("); 
      if(comment == null || comment.length() < 100) 
      { 
      System.out.println(); 
      } 
     String[] strArray = comment.split(" "); 
     for (int i = 0; i < strArray.length; i++) 
      { 
       if(strArray[i].length() > 100) 
       { 
       int iter = strArray[i].length()/100 ; 
       int count = 100 ; 
       int initCount = 0 ; 
       String strReplace = null; 

        for(int j =0 ; j< iter ; j++) 
        { 
         strReplace = strArray[i].substring(initCount ,count); 

         String strToReplace = strReplace + "\n" ; 
         comment = comment.replaceAll(strReplace,strToReplace); 
         //comment = comment.replaceAll("\\)", "\\\\)"); 
         //comment = comment.replaceAll("\\(", "\\\\("); 
         //comment = comment.replaceAll("\\\\", ""); 
         System.out.println(comment); 
         System.out.println(comment.contains("\n")); 
         initCount = count; //+1 ; 
         count = count +100 ; 
        } 

       } 

      } 
    } 


當我跑我得到以下異常:

異常線程 「main」 的java.util.regex .PatternSyntaxException:無與倫比的收盤價')'
附近指數4 HK $ .3)Booking:[email protected])FCR & DOC:[email protected]電話:00852-
23021977傳真: 00852-2

從我的理解我不得不逃離括號「(」,「)」, 我試圖做到這一點(看代碼的註釋部分)有NT任何異常,但換行符我追加到字符串似乎並沒有出現。當解釋爲正則表達式

+0

沒有正確地給你提問。 – 2012-07-30 05:39:25

+1

也許你可以表示這是一個單元測試,以顯示你期望的結果。 – 2012-07-30 05:43:47

+0

@Pramod Kumar該代碼的目的是它將拆分一個字符串與空格作爲分隔符,如果任何字符串拆分數組超過100個字符,我插入一個換行符(\ n)並將原來的新字符串替換。意思是當你刪除上面的代碼中的註釋,我沒有得到例外,但是當我最終打印字符串時,新行(\ n)附加字符不會出現。 – RVP 2012-07-30 05:49:37

回答

2

String.replaceAll usess 正則表達式的第一個參數,如)字符具有特殊的意義。

改爲嘗試String.replace。 (它仍然替換所有出現的給定子字符串。)

+0

非常感謝先生。 – RVP 2012-07-30 05:51:41

相關問題