How can I replace all matches found in Apache POI?

svenmauer profile image svenmauer ・1 min read

The following code I found on StackOverflow replaces only the first match found. I am happy about help how I can replace all found hits. I tried the method "replaceAll" but without result. Because I don't know how to construct a regex. Important: The text must also be replaced in the footer.


Editor guide
florianschaetz profile image
(((Florian Schätz)))

{ } donates repetitions, for example (from the Java Pattern doc)...

X{n} X, exactly n times

So, the only thing you have to do is the escape that:


But of course, inside a String, you have again to escape the backslash, so your solution is...

text = text.replaceAll("\\{City}", "New York")


final String text = "Foo {city} bar {city}.";
System.out.println(text.replaceAll("\\{city}", "New York"));

Results in: Foo New York bar New York.

But honestly, I think such a question is more appropriate for StackOverflow.

svenmauer profile image
svenmauer Author

Thank you for your answer. If I use your code example, the app does not replace anything. What is the reason for this?

florianschaetz profile image
(((Florian Schätz)))

Hard to guess. Upper and lower case? Try to play around with basic, simple examples first before you add the whole POI layer.