简体   繁体   English

在最近出现的子字符串中分割字符串

[英]Split string in latest occurrence of substring

I need help to split string when substring is found, only on latest occurrence 我需要帮助在发现子字符串时拆分字符串,仅在最近一次发生时

 Substring to search(example):123 
 String: 123hello123boy123guy123girl 
 Res: 123hello123boy123guy (result on split[0])

 Ex: hello123boy
 Res:hello 

I'm trying with this function, but this split only on first occource. 我正在尝试使用此功能,但仅在第一次使用时才进行此拆分。

public static String[] getSplitArray(String toSplitString, String spltiChar) {
    return toSplitString.split("(?<=" + spltiChar + ")");
    }

If you want to do it in single split() , this should work: 如果要在单个split()中执行此操作,则应该可以使用:

string.split("123((?!123).)*?$")

Eg: 例如:

String s = "foo123bar123hhh123tillHere123Bang";
System.out.println(s.split("123((?!123).)*?$")[0]);

Outputs: 输出:

foo123bar123hhh123tillHere

Another approach would be, just split("123") then join the elements you required by 123 as delimiter. 另一种方法是,只需split("123")然后将123所需的元素join为分隔符。

You don't need a regex for that, you can simply use String#lastIndexOf : 您不需要正则表达式,只需使用String#lastIndexOf

-> String s = "123hello123boy123guy123girl"

-> s.substring(0, s.lastIndexOf("123"));
|  Expression value is: "123hello123boy123guy"

-> s.substring(s.lastIndexOf("123"));
|  Expression value is: "123girl"

Improvement on Kent 's answer: this will actually give you a split array rather than a single-element array with the first part of your String : Kent答案的改进:实际上,这将为您提供一个拆分数组,而不是String的第一部分的单元素数组:

String[] text = {
        "123hello123boy123guy123girl", // 123hello123boy123guy 
        "hello123boy"// hello
};
for (String s: text) {
    System.out.println(
        Arrays.toString(
            s.split("123(?=((?!123).)*?$)")
        )
    );
}

Output 输出量

[123hello123boy123guy, girl]
[hello, boy]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM