gpt4 book ai didi

java - 替换所有抛出 PatternSyntaxException 的方法

转载 作者:行者123 更新时间:2023-12-02 07:40:11 25 4
gpt4 key购买 nike

看下面的代码:

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 ;
}

}

}
}


当我运行时,出现以下异常:

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

根据我的理解,我必须转义括号'(',')',我尝试这样做(查看代码中的注释部分)没有任何异常,但我附加到字符串的换行符似乎没有出现。

最佳答案

String.replaceAll使用正则表达式作为第一个参数,并且诸如)之类的字符在解释为正则表达式时具有特殊含义。

尝试String.replace反而。 (它仍然会替换给定子字符串的所有出现。)

关于java - 替换所有抛出 PatternSyntaxException 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11715863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com