我有,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;
}
到目前為止我已經嘗試過,但它不起作用
uj5u.com熱心網友回復:
另一種解決方案將使用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("[$1]"); // backreference to group #1
System.err.println(s1.toString());
uj5u.com熱心網友回復:
我建議將結果寫在一個單獨的字串中(帶有增量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());
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/477146.html
