@NotNull @Contract(pure=true) public static String quoteReplacement(@NotNull String s){
  boolean needReplacements=false;
  for (int i=0; i < s.length(); i++) {
    char c=s.charAt(i);
    if (c == '\\' || c == '$') {
      needReplacements=true;
      break;
    }
  }
  if (!needReplacements)   return s;
  StringBuilder sb=new StringBuilder(s.length() * 6 / 5);
  for (int i=0; i < s.length(); i++) {
    char c=s.charAt(i);
    if (c == '\\') {
      sb.append('\\');
      sb.append('\\');
    }
 else     if (c == '$') {
      sb.append('\\');
      sb.append('$');
    }
 else {
      sb.append(c);
    }
  }
  return sb.toString();
}

@ NotNull @ Contract ( pure = true ) public static String quoteReplacement ( @ NotNull String s ) { boolean needReplacements = false ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c == '\\' || c == '$' ) { needReplacements = true ; break ; } } if ( ! needReplacements ) return s ; StringBuilder sb = new StringBuilder ( s . length ( ) * 6 / 5 ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c == '\\' ) { sb . append ( '\\' ) ; sb . append ( '\\' ) ; } else if ( c == '$' ) { sb . append ( '\\' ) ; sb . append ( '$' ) ; } else { sb . append ( c ) ; } } return sb . toString ( ) ; }
this is just an optimized version of matcher . quotereplacement
