简体   繁体   中英

Unable to replace String occurence in java?

I have a StringBuilder object in java that stores some json formatted data created on the fly using the java program. AL i am trying to do is replace occurrence of String one with String two in the StringBuilder object if any. I wrote the below code to replace but it would not work ? Any reason or effecient way to do a simple replace of string ?

StringBuilder json = new StringBuilder ();

public void method1(){

String replacelater =   "   {\"name\":\" <font color=\\\"#FF0000\\\">"+funcvp_name4.trim()+" <\\/font> \",  \"children\":[  ";

callingmethod2();

String replacewith = "   {\"name\":\" <font color=\\\"#FF0000\\\">"+funcvp_name4.trim()+totalempforfuncvp+" <\\/font> \",  \"children\":[  ";

String jsonnew = json.toString();
jsonnew.replaceFirst(replacelater, replacewith);

json.setLength(-1);
json.append(jsonnew);
}

Error:

Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 2
   {"name":" <font color=\"#FF0000\">(7H Cost 806) <\/font> ",  "children":[  
  ^
    at java.util.regex.Pattern.error(Unknown Source)
    at java.util.regex.Pattern.closure(Unknown Source)
    at java.util.regex.Pattern.sequence(Unknown Source)
    at java.util.regex.Pattern.expr(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.util.regex.Pattern.<init>(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.lang.String.replaceFirst(Unknown Source)
    at CreateChart.iterateFuncVPNamesFromArrayList(CreateChart.java:496)
    at CreateChart.getDataFromEMPHCForFuncVp(CreateChart.java:110)
    at CreateChart.main(CreateChart.java:964)

Your code has two main problems. Firstly the first argument of replaceFirst is treated as a regular expression, so things like backslashes and braces are meta characters rather than literal things to search for - to match a literal string with replaceFirst you need to use Pattern.quote .

Secondly Strings in java are immutable - replaceFirst doesn't modify the string it was called on, it returns the result as a new string.

String jsonnew = json.toString().replaceFirst(
  Pattern.quote(replacelater), replacewith);

Alternatively, the replace method treats its first parameter as a literal string rather than a regex but it will replace all occurrences, not just the first one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM