替换所有方法抛出PatternSyntaxException [英] Replace all method throws PatternSyntaxException
问题描述
查看以下代码:
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:
线程中的异常mainjava.util.regex.PatternSyntaxException:无法匹配的结束')'
附近索引4
HK $ .3)预订:virginiawong@fahkco.com.hk4)FCR& DOC:emilywu@fahkco.com.hk电话:00852-
23021977传真:00852-2
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
根据我的理解,我必须逃避parantheses'(',')',
I tr为了做到这一点(看看代码中的注释部分)没有任何异常,但我附加到字符串的换行似乎没有出现。
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.
推荐答案
String.replaceAll
使用正则表达式作为第一个参数,以及)
等字符在被解释为正则表达式时具有特殊含义。
String.replaceAll
usess regular expressions for the first argument, and characters such as )
have special meaning when interpreted as regular expressions.
尝试 String.replace
。 (它仍然替换给定子字符串的所有出现。)
这篇关于替换所有方法抛出PatternSyntaxException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!