package com.obidea.semantika.mapping.parser.r2rml;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.obidea.semantika.util.StringUtils;

public class R2RmlTemplate
{
   private static final Pattern columnInCurlyBraces = Pattern.compile("\\{([^\\}]+)\\}");

   private int mIndex = 1;

   private String mTemplateString;
   private List<String> mColumnNames = new ArrayList<String>();

   public R2RmlTemplate(String templateString)
   {
      mTemplateString = templateString;
      process(templateString);
   }

   public String getTemplateString()
   {
      return mTemplateString;
   }

   public List<String> getColumnNames()
   {
      return mColumnNames;
   }

   private void process(String templateString)
   {
      Matcher m = columnInCurlyBraces.matcher(templateString);
      while (m.find()) {
         String arg = m.group(2);
         if (!StringUtils.isEmpty(arg)) {
            mTemplateString.replace(arg, mIndex+"");
            mColumnNames.add(arg);
            mIndex++;
         }
      }
   }
}

@@ -911,17 +911,17 @@
 m.group(
-2
+1
 );%0A     
@@ -988,30 +988,69 @@
 ring
-.replace(arg,
+ = mTemplateString.replace(%22%7B%22 + arg + %22%7D%22, %22%7B%22 +
  mIndex
-+%22
+ + %22%7D
 %22);%0A

Fix the out of bound index exception, the index for the matcher should be 1 instead of 2. I also fix the template string replace to use the curly braces to ensure the string replacement to be perfectly correct.