How can I replace all matches found in Apache POI?

github logo ・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.

twitter logo DISCUSS (3)
markdown guide

{ } 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.


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


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

Classic DEV Post from Apr 30

Who's looking for open source contributors? (April 30th edition)

svenmauer profile image