DEV Community

svenmauer
svenmauer

Posted on

How can I replace all matches found in Apache POI?

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.

Top comments (3)

Collapse
 
florianschaetz profile image
(((Florian Schätz))) • Edited

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

\{City}

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

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

Example:

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.

Collapse
 
svenmauer profile image
svenmauer

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

Collapse
 
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.