3 回答
TA贡献2012条经验 获得超12个赞
您不应以“优雅的方式”进行编码。您可以采用简单的解决方案(意味着易于编写/读取/维护(并非在所有情况下都尽可能快),也可以采用满足您的要求(大小,速度等)的解决方案。
一个可能的简单解决方案(基于您的示例)可能是
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: 213home
value: 234tower first: last: 234tower
value: 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: test123
value: test123abc first: test123 last: abc
TA贡献2021条经验 获得超8个赞
这是一种非正则表达式方法,在该方法中,您可以在字符串中搜索数字的索引(如果有的话)。然后,您只需得到substring结果即可。如果找不到数字,请注意三元选择。
public class StackOverflow {
public static void main(String[] args) {
String[] data = { "test213home", "234tower", "test", "foo42bar23" };
for (String d : data) {
System.out.println("Before digit: " + beforeDigit(d));
System.out.println("After digit : " + afterDigit(d));
System.out.println("");
}
}
private static String beforeDigit(String data) {
int index = findDigitIndex(data);
return index > -1
? data.substring(0, index)
: data.substring(0);
}
private static String afterDigit(String data) {
int index = findDigitIndex(data);
return index > -1
? data.substring(index)
: data.substring(0);
}
private static int findDigitIndex(String data) {
int index = -1;
for (int i = 0; i < data.length(); i++) {
if (Character.isDigit(data.charAt(i))) {
index = i;
break;
}
}
return index;
}
}
结果:
Before digit: test
After digit : 213home
Before digit:
After digit : 234tower
Before digit: test
After digit : test
Before digit: foo
After digit : 42bar23
添加回答
举报