Replace all method throws PatternSyntaxException

大憨熊 提交于 2019-12-02 21:09:20

问题


look at the following code:

String comment = "1)FCR pick up in Hong Kong2)Local charges will be paiy in Hong Kong & in HK$.3)Booking:virginiawong@fahkco.com.hk4)FCR&DOC:emilywu@fahkco.com.hkTel: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 ;
                    } 

                }   

            }
    }


When I run I get the following exception:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unmatched closing ')'
near index 4 HK$.3)Booking:virginiawong@fahkco.com.hk4)FCR&DOC:emilywu@fahkco.com.hkTel:00852-
23021977Fax:00852-2

From my understanding I have to escape the parantheses'(',')', I tried to do this(look at the commented part in the code)there was nt any exception but the newline I am appending to the string doesn't seem to appear.


回答1:


String.replaceAll usess regular expressions for the first argument, and characters such as ) have special meaning when interpreted as regular expressions.

Try String.replace instead. (It still replaces all occurrences of the given substring.)



来源:https://stackoverflow.com/questions/11715863/replace-all-method-throws-patternsyntaxexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!