'How do replace digit enclosed dot with braces in java

I am having String details=employee.details.0.name but i want to have it like String details=employee.details[0].name What would be the easiest way to achieve that? i am using java.

 private static String getPath(String path) {
    Pattern p = Pattern.compile( "\\.(\\d+)\\." );
        Matcher m = p.matcher( path );
           while(m.find()){
               path = path.replaceFirst(Pattern.quote("."), m.group(1));
        }
    return path;
}

i have tried so far but its not working



Solution 1:[1]

I would suggest to write the result in a separate string (with an incremental StringBuilder), otherwise it will mess up the match ranges that Matcher.find reports.

final String s = "employee.1.details.0.name.5";
        
StringBuilder s1 = new StringBuilder(); // a builder for the result
// pattern: a dot, followed by a number, followed (as lookahead) by either a dot or the end of input
Pattern p = Pattern.compile("[.]([0-9]+)(?=([.]|$))");       
Matcher m = p.matcher(s);

int i = 0; // current position in source string
while (m.find()) {
   s1.append(s.substring(i, m.start()));
   s1.append("[" + m.group(1) + "]");
   i = m.end();
}
s1.append(s.substring(i, s.length())); // copy remaining part

System.err.println(s1.toString());

Solution 2:[2]

Another solution would use Matcher.replaceAll with a backreference to the matched group which contained the ordinal number:

final String s = "employee.1.details.0.name";
        
Pattern p = Pattern.compile("[.]([0-9]+)(?=([.]|$))");       
Matcher m = p.matcher(s);
String s1 = m.replaceAll("[$1]"); // backreference to group #1

System.err.println(s1.toString());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Michail Alexakis