Use Matcher
and Matcher#appendReplacement()
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllEx {
public static void main(String[] args) {
String input = "randomPrefix"
+ "/ima?pth=randomInfix/ima?pth="
+ "/ima?pth=randomInfix/ima?pth="
;
Pattern p = Pattern.compile("/ima\\?pth=");
Matcher m = p.matcher(input);
int i = 1;
StringBuffer sb = new StringBuffer();
System.out.println("input is\n" + input + "\n");
while (m.find()) {
m.appendReplacement(sb, "/ima?pth="+"**"+i+"**");
i++;
}
System.out.println("output is\n" + sb.toString() + "\n");
}
}
The output of the above program would be:
input is
randomPrefix/ima?pth=randomInfix/ima?pth=/ima?pth=randomInfix/ima?pth=
output is
randomPrefix/ima?pth=**1**randomInfix/ima?pth=**2**/ima?pth=**3**randomInfix/ima?pth=**4**
Updated
Here is another example demonstrating the use of Matcher#appendReplacement()
-- with OP's new input example.
private static void example2() {
String input = "<img src=\"cid:1\"/>"
private static void example2() {
String input = "<img src=\"cid:1\"/>"
// + "<span style=\"font-size:14pt;font-family:'Times New Roman';\">"
// + "</span><div>"
// + "<span style=\"font-size:14pt;font-family:'Times New Roman';\">"
// + "<br /></span></div>"
// + "<div>"
// + "<span style=\"font-size:14pt;font-family:'Times New Roman';\">"
// + "<br /></span></div>"
// + "<div>"
// + "<span style=\"font-size:14pt;font-family:'Times New Roman';\">"
// + "</span><br /><div style=\"display:none;\">"
// + "</div></div><div>"
// + "<span style=\"font-size:14pt;font-family:'Times New Roman';\">"
// + "<br /></span></div><div>"
+ "<img src=\"/XP/image?path=09021b5e80061f2c\"/>"
// + "<span style=\"font-size:14pt;font-family:'Times New Roman';\">"
// + "<br /></span>"
+ "<img src=\"/XP/image?path=09021b5e80061f2c\"/>"
+ "<img src=\"/XP/image?path=09021b5e80061f2c\"/>"
;
Pattern p = Pattern.compile("<img src=\\\"/XP/image\\?path=09021b5e80061f2c\\\"/>");
Matcher m = p.matcher(input);
int i = 2;
StringBuffer sb = new StringBuffer();
System.out.println("input is\n" + input + "\n");
while (m.find()) {
String replacement = String.format("<img src=\"cid: %d\"/>", i);
m.appendReplacement(sb, replacement);
i++;
}
System.out.println("output is\n" + sb.toString() + "\n");
}
This would be the program output:
input is
<img src="cid:1"/><img src="/XP/image?path=09021b5e80061f2c"/><img src="/XP/image?path=09021b5e80061f2c"/><img src="/XP/image?path=09021b5e80061f2c"/>
output is
<img src="cid:1"/><img src="cid: 2"/><img src="cid: 3"/><img src="cid: 4"/>