繁花如伊
您不应以“优雅的方式”进行编码。您可以采用简单的解决方案(意味着易于编写/读取/维护(并非在所有情况下都尽可能快),也可以采用满足您的要求(大小,速度等)的解决方案。一个可能的简单解决方案(基于您的示例)可能是String[] strings = { "test213home", "234tower", "test", "foo42bar23"};for (String string : strings) { String first = string.replaceFirst("^([^\\d]*).*", "$1"); String last = string.replaceFirst("^[^\\d]*(.*)", "$1"); System.out.printf("value: %-11s first: %-4s last: %s%n", string, first, last);}输出value: test213home first: test last: 213homevalue: 234tower first: last: 234towervalue: test first: test last: value: foo42bar23 first: foo last: 42bar23对于正则表达式的解释,我建议您阅读有关“正则表达式”的Java教程。编辑在评论中找到您的问题的摘要。String[] strings1 = { "12345test123", "test123abc"};for (String string : strings1) { String first = string.replaceFirst("^([^\\d]*[\\d]*).*", "$1"); String last = string.replaceFirst("^[^\\d]*[\\d]*(.*)", "$1"); System.out.printf("value: %-12s first: %-7s last: %s%n", string, first, last);}输出value: 12345test123 first: 12345 last: test123value: test123abc first: test123 last: abc