我想将当前代码转换为Java7 diamond operator
。
我有以下正则表达式来查找和替换。
查找
new (\w+)<.+>
替换:
new $1<>
问题在于 也被替换为匿名类。由于这个我得到编译错误。 那么如何编写避免内部类的正则表达式呢?
答案 0 :(得分:0)
试试这个:(?s)new (\w+)<.+>(\(.*?\);)
String test = "List<String> t = new ArrayList<String>();";
System.out.println(test.replaceAll("(?s)new (\\w+)<.+>(\\(.*?\\);)", "new $1<>$2"));
String test2 = "List<String> t = new ArrayList<String>(getList());";
System.out.println(test2.replaceAll("(?s)new (\\w+)<.+>(\\(.*?\\);)", "new $1<>$2"));
String test3 = "List<String> t = new ArrayList<String>(\n\tgetList(\n\t\tanotherMethod()\n\t)\n);";
System.out.println(test3.replaceAll("(?s)new (\\w+)<.+>(\\(.*?\\);)", "new $1<>$2"));
String test4 = "List<String> t = new List<String>(){ /* implementation */ };";
System.out.println(test4.replaceAll("(?s)new (\\w+)<.+>(\\(.*?\\);)", "new $1<>$2"));
String test5 = "List<String> t = new List<String>()\n{\n\t/* implementation */\n};";
System.out.println(test5.replaceAll("(?s)new (\\w+)<.+>(\\(.*?\\);)", "new $1<>$2"));
打印:
List<String> t = new ArrayList<>();
List<String> t = new ArrayList<>(getList());
List<String> t = new ArrayList<>(
getList(
anotherMethod()
)
);
List<String> t = new List<String>(){ /* implementation */ };
List<String> t = new List<String>()
{
/* implementation */
};