简体   繁体   English

首先在Java中找到String

[英]Split by first found String in Java

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

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. limit参数控制模式的应用次数,因此会影响结果数组的长度。 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大于零,那么模式将最多应用n - 1次,数组的长度将不大于n ,并且数组的最后一个条目将包含除最后一个匹配分隔符之外的所有输入。

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

See javadoc for more info 有关更多信息,请参阅javadoc

EDIT : Escaped bracket, as per @Pedro's comment below. 编辑 :Escaped支架,根据@ Pedro的评论如下。

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

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

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