Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Before using the function, I'm sure that: paragraph.getText().contains("<#" + tag + "#>") == true
- private static void editParagraphWithData(XWPFParagraph paragraph, String tag, String remplacement) {
- int currentRun = 0;
- List<Integer> runsToRemove = new LinkedList<Integer>();
- StringBuilder newText = new StringBuilder();
- int runToEdit = 0;
- String surroundedTag = "<#" + tag + "#>";
- // Until we didn't find the tag
- while (!newText.toString().contains(surroundedTag)) {
- // Until we didn't find the first corresponding run
- while (paragraph.getRuns().size() > currentRun && !paragraph.getRuns().get(currentRun).text().contains("<#")) {
- currentRun++;
- }
- runToEdit = currentRun;
- newText.append(paragraph.getRuns().get(runToEdit).text());
- currentRun++;
- // Until we didn't find the end of the tag if it's divided in many runs
- while (paragraph.getRuns().size() > currentRun && !paragraph.getRuns().get(currentRun).text().contains("#>")) {
- runsToRemove.add(currentRun);
- newText.append(paragraph.getRuns().get(currentRun).text());
- currentRun++;
- }
- // If we didn't find the right tag
- if (!newText.toString().contains(surroundedTag)) {
- runsToRemove.clear();
- newText = new StringBuilder();
- }
- }
- // Replace the tag
- paragraph.getRuns().get(runToEdit).setText(newText.toString().replaceAll(surroundedTag, remplacement), 0);
- // Remove the remaining tags if we need to (in reverse order)
- Collections.reverse(runsToRemove);
- for (Integer runToRemove : runsToRemove) {
- paragraph.removeRun(runToRemove);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement