Search code examples
javaregexreplaceall

How to fix the following RegEx?


I've the following piece of code. I use the Case-insensitve pattern modifier so it will find any occurrence, but what I want is the replacement to be exactly the chars that matched the pattern, keeping the case. How could I fix this?

    String str = "Ten tender tEens";
    String substr = "te";
    str = str.replaceAll("(?i)"+substr, "("+substr+")");

    System.out.println( str );

Desired output: (Te)n (te)nder (tE)ens

Received output: (te)n (te)nder (te)ens


Solution

  • replaceAll() work as the same ways as matcher(string).replaceAll(exp): To make this work and for better understanding you can break the code like :

         String str = "Ten tender tEens";
         Pattern pattern=Pattern.compile("(?i)(te)");
         Matcher matcher=pattern.matcher(str);
    
         System.out.println(  matcher.replaceAll("$1"));
    

    Combining these steps you can use (does the same):

    String substr = "te";
    str = str.replaceAll("(?i)("+substr+")", "($1)");