我想将当前代码转换为Java7 diamond operator。我有下面的正则表达式来查找和替换。
查找
new (\w+)<.+>取代:
new $1<> 问题是,它也被替换为匿名类。因此,我得到了编译错误。那么,如何编写避免内部类的正则表达式呢?
发布于 2014-11-24 11:39:04
试试这个:(?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 */
};https://stackoverflow.com/questions/27103745
复制相似问题