按 Java 中第一个找到的字符串拆分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9873674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:43:48  来源:igfitidea点击:

Split by first found String in Java

javaregexjakarta-eejava-6

提问by Max_Salah

is ist possible to tell String.split("(") function that it has to split only by the first found string "("?

是否可以告诉 String.split("(") 函数它必须仅由第一个找到的字符串 "("?

Example:

例子:

String test = "A*B(A+B)+A*(A+B)";
test.split("(") should result to ["A*B" ,"A+B)+A*(A+B)"]
test.split(")") should result to ["A*B(A+B" ,"+A*(A+B)"]

回答by ruakh

Yes, absolutely:

是的,一点没错:

test.split("\(", 2);

As the documentation for String.split(String,int)explains:

正如文档String.split(String,int)解释的那样:

The limitparameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit nis greater than zero then the pattern will be applied at most n- 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

limit参数控制应用模式的次数,因此会影响结果数组的长度。如果限制n大于零,则该模式将最多应用n- 1 次,数组的长度将不大于n,并且数组的最后一个条目将包含最后一个匹配的分隔符之外的所有输入。

回答by KingCronus

test.split("\(",2);

See javadocfor more info

有关更多信息,请参阅javadoc

EDIT: Escaped bracket, as per @Pedro's comment below.

编辑:转义括号,根据下面@Pedro 的评论。

回答by óscar López

Try with this solution, it's generic, faster and simpler than using a regular expression:

试试这个解决方案,它比使用正则表达式更通用、更快、更简单:

public static String[] splitOnFirst(String str, char c) {
    int idx = str.indexOf(c);
    String head = str.substring(0, idx);
    String tail = str.substring(idx + 1);
    return new String[] { head, tail} ;
}

Test it like this:

像这样测试它:

String test = "A*B(A+B)+A*(A+B)";
System.out.println(Arrays.toString(splitOnFirst(test, '(')));
System.out.println(Arrays.toString(splitOnFirst(test, ')')));