[英]How do I convert underscore into human-readable names in Java?
I'd like to write a method that converts CamelCase into a human-readable name. 我想编写一种将CamelCase转换为人类可读名称的方法。 This is very similar to this question but now with underscore. 这与这个问题非常相似,但现在带有下划线。
Here's the test case: 这是测试用例:
public void testSplitUnderscore() {
assertEquals("lowercase", splitUnderscore("lowercase"));
assertEquals("Class", splitUnderscore("Class"));
assertEquals("My Class", splitUnderscore("My_Class"));
assertEquals("HTML", splitUnderscore("HTML"));
assertEquals("PDF Loader", splitUnderscore("PDF_Loader"));
assertEquals("A String", splitUnderscore("A_String"));
assertEquals("Simple XML Parser", splitUnderscore("Simple_XML_Parser"));
assertEquals("GL 11 Version", splitUnderscore("GL_11_Version"));
assertEquals("99 Bottles", splitUnderscore("99_Bottle"));
assertEquals("May 5", splitUnderscore("May_5"));
assertEquals("BFG 9000", splitUnderscore("BFG_9000"));
assertEquals("beginning", splitUnderscore("_beginning"));
assertEquals("end", splitUnderscore("end_"));
assertEquals("double middle", splitUnderscore("double__middle"));
assertEquals("double end", splitUnderscore("double_end__"));
assertEquals("double start", splitUnderscore("__double_start"));
assertEquals("double start middle end", splitUnderscore("__double_start__middle_end__"));
}
A naive way of accomplishing this would be to replace every '_'
with a ' '
, and then trim the whitespaces off the final string: 一种简单的方法是将每个'_'
替换为' '
,然后将最后一个字符串的空白修剪掉:
public static String splitUnderscore(String s) {
return s.replace("_", " ").trim();
}
While the above works for most cases, to handle multiple adjacent underscores we could use a regular expression to replace any number of consecutive underscores with a single ' '
: 尽管上面的代码在大多数情况下都有效,但是要处理多个相邻的下划线,我们可以使用正则表达式用单个' '
替换任意数量的连续下划线:
public static String splitUnderscore(String s) {
return s.replaceAll("_{1,}", " ").trim();
}
以下应该工作:
String.replace('_', " ").trim();
You should have a couple more test cases: 您应该再有几个测试用例:
assertEquals("A String", splitUnderscore("double__middle"));
assertEquals("A String", splitUnderscore("double_end__"));
assertEquals("A String", splitUnderscore("__double_start"));
assertEquals("A String", splitUnderscore("__double_start__middle_end__"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.