我想编写一个将 CamelCase 转换为人类可读名称的方法。
这是测试用例:
public void testSplitCamelCase() { assertEquals("lowercase", splitCamelCase("lowercase")); assertEquals("Class", splitCamelCase("Class")); assertEquals("My Class", splitCamelCase("MyClass")); assertEquals("HTML", splitCamelCase("HTML")); assertEquals("PDF Loader", splitCamelCase("PDFLoader")); assertEquals("A String", splitCamelCase("AString")); assertEquals("Simple XML Parser", splitCamelCase("SimpleXMLParser")); assertEquals("GL 11 Version", splitCamelCase("GL11Version")); }
这适用于您的测试用例:
static String splitCamelCase(String s) { return s.replaceAll( String.format("%s|%s|%s", "(?<=[A-Z])(?=[A-Z][a-z])", "(?<=[^A-Z])(?=[A-Z])", "(?<=[A-Za-z])(?=[^A-Za-z])" ), " " ); }
这是一个测试工具:
String[] tests = { "lowercase", // [lowercase] "Class", // [Class] "MyClass", // [My Class] "HTML", // [HTML] "PDFLoader", // [PDF Loader] "AString", // [A String] "SimpleXMLParser", // [Simple XML Parser] "GL11Version", // [GL 11 Version] "99Bottles", // [99 Bottles] "May5", // [May 5] "BFG9000", // [BFG 9000] }; for (String test : tests) { System.out.println("[" + splitCamelCase(test) + "]"); }
它使用零长度匹配的正则表达式和lookbehind 并期待找到插入空格的位置。基本上有 3 种模式,我String.format将它们组合在一起以使其更具可读性。
String.format
这三种模式是:
XMLParser AString PDFLoader /\ /\ /\
MyClass 99Bottles /\ /\
GL11 May5 BFG9000 /\ /\ /\