I want to replace all occurrences of particular string with different UUID's. For example,
content = content.replaceAll("xyz", "xyz" + generateUUID());
but problem here is that all the "xyz"
's will get replaced by same UUID. But I want that each "xyz"
gets replaced by an individual unique ID. How can this be done?
You can do this using Matcher.appendReplacement
. This will give you the replaceAll
functionality of a complete regex (not just a static String
). Here, I use uidCounter
as a very simple generateUUID
; you should be able to adapt this to your own generateUUID
function.
public class AppendReplacementExample {
public static void main(String[] args) throws Exception {
int uidCounter = 1000;
Pattern p = Pattern.compile("xyz");
String test = "abc xyz def xyz ghi xyz";
Matcher m = p.matcher(test);
StringBuffer sb = new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, m.group() + uidCounter);
uidCounter++;
}
m.appendTail(sb);
System.out.println(sb.toString());
}
}
Output:
abc xyz1000 def xyz1001 ghi xyz1002
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With