glass
glass

Reputation: 179

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?

Upvotes: 2

Views: 2141

Answers (2)

anubhava
anubhava

Reputation: 785186

You can use this lookbehind assertion in your regex:

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

RegEx Demo

Upvotes: 1

Nir Levy
Nir Levy

Reputation: 12953

Try:

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

Upvotes: 2

Related Questions