The question is possibly incorrect, but the solution was not found: For example, there is such a file:

{ "xxxxxxxx": "present/xxxxxxxxxxxxx", "xxxxxxx": { "xxxxxxx": "present/xxxxxxxxxxxx", "xxxxxxx": "present/xxxxxxxxxx" } } 

The task is to replace the word "present" with "test: present", and to do this exactly as many times as necessary. That is, if you need 2 times, the result should be like this:

 { "xxxxxxxx": "test:present/xxxxxxxxxxxxx", "xxxxxxx": { "xxxxxxx": "test:present/xxxxxxxxxxxx", "xxxxxxx": "present/xxxxxxxxxx" } } 

Initially, neither the file size nor the number of the required lines is known. I tried using String :: replaceFirst in a loop, but in two passes it will change the same string, since one contains the other: present -> test:present -> test:test:present . At the moment my code looks like this:

 String writable = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); for(int z = 0; z < stepOnFile; ++z) { writable = writable.replaceFirst("present", "test:present"); } 

stepOnFile is just the number of repetitions.

  • I'm afraid of this and the problem. There are several hundreds of such files, each from 1 to 5 MB. I do not want to slow down the program ... I was thinking about using regular expressions, but I could not find a solution - mousecray

1 answer 1

 public static String replaceTimes(Pattern pattern, String replacement, String input, int times) { Matcher matcher = pattern.matcher(input); StringBuffer out = new StringBuffer(); for (int i = 0; i < times && matcher.find(); i++) { matcher.appendReplacement(out, replacement); } return matcher.appendTail(out).toString(); } 
 String text = "{\n" + " \"xxxxxxxx\": \"present/xxxxxxxxxxxxx\",\n" + " \"xxxxxxx\": {\n" + " \"xxxxxxx\": \"present/xxxxxxxxxxxx\",\n" + " \"xxxxxxx\": \"present/xxxxxxxxxx\"\n" + " }\n" + "}"; Pattern pattern = Pattern.compile("present"); System.out.println(replaceTimes(pattern, "test:present", text, 2)); 
  • And what role does Pattern play here? - mousecray
  • @mousecray the role of a regular expression :) - extrn 8:17 pm
  • My God, it works absolutely in the right way! Thank you. I thought about using regex, but I understand this too poorly. StringBuffer saves from repetition, right? - mousecray
  • A StringBuffer is simply a tool for more efficiently assembling a string without full copying with each replacement. All the magic in appendReplacement / appendTail . The first one complements the resulting string with text for every match, making a replacement along the way, the second copies the remaining part of the input string to the result unchanged. - extrn
  • Thank you very much. I will go again to read about the regex :) - mousecray