Home > Software engineering >  How do replace digit enclosed dot with braces in java
How do replace digit enclosed dot with braces in java

Time:05-18

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

CodePudding user response:

I would suggest to write the result in a separate string, otherwise it will mess up the source string (and 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());
  • Related