无限制拆分会拆分整个字符串,但如果设置了限制,它会向左分割到该限制.我怎么能在右边这样做呢?
"a.b.c".split("[.]", 2); // returns ["a", "b.c"]
Run Code Online (Sandbox Code Playgroud)
我想要
"a.b.c".splitRight("[.]", 2); // to return ["a.b", "c"]
Run Code Online (Sandbox Code Playgroud)
编辑:我想要一个通用的解决方案,就像分裂但反转,所以我添加一个更复杂的例子
我想要
"a(->)b(->)c(->)d".splitRight("\\(->\\)", 3); // to return ["a(->)b", "c", "d"]
Run Code Online (Sandbox Code Playgroud)
您可以使用先行匹配:
"a.b.c".split("[.](?=[^.]*$)")
Run Code Online (Sandbox Code Playgroud)
在这里你说"我想只通过那个没有其他点后面的点".
如果你想分割最后N个点,你可以用这个(甚至更丑陋的方式)推广这个解决方案:
"dfsga.sdgdsb.dsgc.dsgsdfg.dsdg.sdfg.sdf".split("[.](?=([^.]*[.]){0,3}[^.]*$)");
Run Code Online (Sandbox Code Playgroud)
替换3为N-2.
但是我会写一个简短的静态方法:
public static String[] splitAtLastDot(String s) {
int pos = s.lastIndexOf('.');
if(pos == -1)
return new String[] {s};
return new String[] {s.substring(0, pos), s.substring(pos+1)};
}
Run Code Online (Sandbox Code Playgroud)
我会尝试这样的事情:
public List<String> splitRight(String string, String regex, int limit) {
List<String> result = new ArrayList<String>();
String[] temp = new String[0];
for(int i = 1; i < limit; i++) {
if(string.matches(".*"+regex+".*")) {
temp = string.split(modifyRegex(regex));
result.add(temp[1]);
string = temp[0];
}
}
if(temp.length>0) {
result.add(temp[0]);
}
Collections.reverse(result);
return result;
}
public String modifyRegex(String regex){
return regex + "(?!.*" + regex + ".*$)";
}
Run Code Online (Sandbox Code Playgroud)
split 的正则表达式被另一个包裹,因此对于\\.,您将得到:\\.(?!.*\\..*$), 在最后一次出现分隔符时进行匹配和拆分。使用此正则表达式将字符串拆分多次,将结果数组的第二个元素添加到列表中,下一次拆分在结果数组的第一个元素上完成。
上述方法对示例字符串的效果符合预期。