我尝试使用此代码创建代码美化器。但如果它找到 a "}"
,美化就会破坏。如何使用此代码修复它?
String code = "class Demo{public static void main(String[] args) {System.out.println(\"ABC\");if(\"A\".equals(\"A\")){return \"A\";}System.out.println(\"ABC\");}}";
String outtext = code;
String repfrom = "{";
String repto = "{\n";
Pattern p = Pattern.compile(repfrom, Pattern.LITERAL);
Matcher m = p.matcher(outtext);
int counter = 0;
StringBuffer sb = new StringBuffer();
while (m.find()) {
counter++;
m.appendReplacement(sb, repto + (tab += "\t"));
}
m.appendTail(sb);
String newtext = sb.toString().replace(";", ";\n" + tab);
String replace = "";
for (int i = 0; i < counter; i++) {
replace = newtext.replace("}", "\b}");
}
System.out.println(replace);
我的输出是:
class Demo{
public static void main(String[] args) {
System.out.println("ABC");
if("A".equals("A")){
return "A";
}System.out.println("ABC");
}