Search code examples
javaregexreplacereplaceall

Replace text between two symbols with regex


This should be simple, but I don't know regex... I've seen many similar questions here but none solve precisely what I want. I have this string:

String s = "randomStuff§dog€randomStuff"; //randomStuff is random letters and numbers, it's not a word

and I want to replace dog (it's not always dog, don't include it in the regex) with bird, so the output should be:

String s = "randomStuff§bird€randomStuff";

What I'm using now is

s = s.replaceAll("\\§(.*?)\\€", "bird");

but this deletes also the § and € symbols. How to keep those symbols too?


Solution

  • You can use this lookbehind assertion in your regex:

    s = s.replaceAll("(?<=§)[^€]*", "bird");
    

    RegEx Demo