0

I have a string which contains several placeholder.. so I need to iterate over the String and replace name => mike, gender => male

   String text = "Hi {#name} you are a {#gender}";
   String[] values = {"Mike","Male"};

    int count = -1;

    Pattern pattern = Pattern.compile("(\\{)(#)(.+)(\\})");
    Matcher matcher = pattern.matcher(text);
    StringBuffer buffer = new StringBuffer();

        while (matcher.find()) {
          count++;
          matcher.appendReplacement(buffer, values[count]);
        }
        matcher.appendTail(buffer);

        System.out.println(buffer.toString());

It stops to: 'Hi mike'

I need the entire line to be replaced with new values

Thanks

John Michael
  • 67
  • 3
  • 14
  • 2
    [Replace `.+` with `.+?`](https://ideone.com/bwIRQd) – Wiktor Stribiżew Oct 23 '17 at 13:04
  • 1
    Check this [regex compile online](https://regex101.com/). it realy helps working with regex. you just need to be carefull because special chars are don´t need to be escaped so \\ = \. – LenglBoy Oct 23 '17 at 13:07
  • `([{][#][a-zA-Z]+[}])` for both words and `([{][#][name]+[}])` for specific one. Also a good page is [this](http://regex-testdrive.com/en/dotest) – LenglBoy Oct 23 '17 at 13:16

0 Answers0