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
Genzotto
1,9746 gold badges29 silver badges49 bronze badges
-
You could capture the number using parentheses and use that in the replacement, I thinkawksp– awksp2014年06月10日 16:21:09 +00:00Commented Jun 10, 2014 at 16:21
1 Answer 1
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
Pshemo
125k26 gold badges194 silver badges280 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Genzotto
That's it! I did it in a more complex way: "(@@MyText\[)(\\d*)(\])", and then using 2,ドル but I prefer your solution. Thank you!
lang-java