Search code examples
javaregexreplaceall

Replace a string at particular position with another string without hardcoding in java


I am reading a string from file at a specific position and i need to make some conversions by calling a function and the resultant string has to be replaced in the same position. Below code throws me Illegal repetition error since my string contains characters such as '}','{'. I dont know how to escape these characters when it is specifically not hardcoded. Please help.

    String MFstr = strLine.substring(612,623);
    StringBuilder sbMFstr=new StringBuilder (strLine.substring(612,623));


    String temp="";
    if (mfn.isNegativeMFOrNegativeOverPunch(MFstr)){
        temp = "-"+MFstr;}
    else{
    temp=MFstr;}
    String number=mfn.MForOverPunchToNumber(MFstr);
    if( temp.startsWith("-")){
        //Positive is false
        number = "0" + number;

    }
    strLine.replaceAll(MFstr, number);  //This line throws Exception

Solution

  • The first parameter of replaceAll is a regular expression. { and } are occurrence characters in regex. You could do

    strLine = strLine.replaceAll(Pattern.quote(mfStr), number);  
    

    or simply

    strLine = strLine.replace(mfStr, number);