0

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

asked Jun 10, 2014 at 16:18
1
  • You could capture the number using parentheses and use that in the replacement, I think Commented Jun 10, 2014 at 16:21

1 Answer 1

4

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
answered Jun 10, 2014 at 16:21
Sign up to request clarification or add additional context in comments.

1 Comment

That's it! I did it in a more complex way: "(@@MyText\[)(\\d*)(\])", and then using 2,ドル but I prefer your solution. Thank you!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.