在Java中被第一个发现的字符串分割

时间:2021-11-27 02:14:50

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)"]

3 个解决方案

#1


48  

Yes, absolutely:

是的,绝对:

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

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

如String.split(String,int)文档所述:

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is 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.

限制参数控制应用模式的次数,因此影响结果数组的长度。如果限制n大于0,那么模式将被应用最多n - 1次,数组的长度将不大于n,并且数组的最后一个条目将包含超过最后匹配的分隔符的所有输入。

#2


4  

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

See javadoc for more info

有关更多信息,请参见javadoc。

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

编辑:转义括号,如下面@Pedro的评论所示。

#3


2  

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, ')')));

#1


48  

Yes, absolutely:

是的,绝对:

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

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

如String.split(String,int)文档所述:

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is 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.

限制参数控制应用模式的次数,因此影响结果数组的长度。如果限制n大于0,那么模式将被应用最多n - 1次,数组的长度将不大于n,并且数组的最后一个条目将包含超过最后匹配的分隔符的所有输入。

#2


4  

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

See javadoc for more info

有关更多信息,请参见javadoc。

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

编辑:转义括号,如下面@Pedro的评论所示。

#3


2  

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, ')')));