如何在 java 中用大括号替换数字括起来的点

How do replace digit enclosed dot with braces in java

我有 String details=employee.details.0.name,但我想像 String details=employee.details[0].name 那样拥有它,最简单的方法是什么?我正在使用 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;
}

到目前为止我已经试过了,但还是不行

我建议将结果写在一个单独的字符串中(使用增量 StringBuilder),否则它会弄乱 Matcher.find 报告的匹配范围。

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());

另一种解决方案是使用 Matcher.replaceAll 和对包含序号的匹配组的反向引用:

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

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