String (String input, Pattern pattern, String template, boolean shouldEscape) { Matcher matcher = pattern.matcher(input); int start = matcher.matches() ? matcher.start(1) : -1; if(!shouldEscape){ if(start == -1){ return input; } else { return input.substring(0, start) + FILE_HEADER_TEMPLATE_PLACEHOLDER + input.substring(matcher.end(1)); } } StringBuilder builder = new StringBuilder(input.length() + 10); for (int i = 0; i < input.length(); i++) { if (start == i) { builder.append(template); //noinspection AssignmentToForLoopParameter i = matcher.end(1); } char c = input.charAt(i); if (c == '$') { builder.append("#[[\\$]]#"); continue; } if (c == '#') { builder.append('\\'); } builder.append(c); } return builder.toString(); }