Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use replaceAll on string but call method for replacing the text on each occurrence of a match

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?

like image 516
Nick Div Avatar asked Oct 15 '25 04:10

Nick Div


1 Answers

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
like image 175
durron597 Avatar answered Oct 16 '25 18:10

durron597



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!