Genzotto
Genzotto

Reputation: 1974

Replace pattern in Java

I have the following text:

String text = "lorem ipsum @@MyText[1] lorem ipsum @@MyText[22]";

And I want to replace it by:

String text = "lorem ipsum /my/url/1 lorem ipsum /my/url/22;

I have done the following:

String newText = text.replaceAll("@@MyText\\[\\d*\\]", "/my/url/%s");

But in this way I get:

"lorem ipsum /my/url/%s lorem ipsum /my/url/%s;

How could I replace the given text but still conservating the number in the brackets?

Thank you very much in advance

Upvotes: 0

Views: 95

Answers (1)

Pshemo
Pshemo

Reputation: 124225

You need to place number found in [...] in separate group and use match from that group in replacement via $id where id represents number of that group.

Use

replaceAll("@@MyText\\[(\\d+)\\]",       "my/url/$1")
//                     ^^^^^^ group 1            ^^ part matched by group 1

Upvotes: 4

Related Questions