我想在第一个大括号内分割字符串。我怎么能在java中做到这一点
Input String 1: text2(text3, text4), text5(text6, text7)
String1: text2(text3, text4)
String2: text5(text6, text7)
Input String 2: text2, text3(text4, text5(text6, text7, text8))
String1: text2
String2: text3(text4, text5(text6, text7, text8))
输入字符串可以具有任意数量的级别。请假设输入字符串具有匹配的大括号。
提前致谢
答案 0 :(得分:2)
package ic.ac.uk.relationshipvisualiser.app;
import java.util.ArrayList;
import java.util.List;
public class tmpTest3 {
public static List<String> process(String p_inp) {
List<String> res = new ArrayList<String>();
p_inp = p_inp.trim();
int numberOfOpenBracketsEncountered = 0;
String t = "";
String cur = "";
for (int c=0;c<p_inp.length();c++) {
cur = p_inp.substring(c,c+1);
if (cur.equals("(")) {
numberOfOpenBracketsEncountered++;
}
if (cur.equals(")")) {
numberOfOpenBracketsEncountered--;
}
if (cur.equals(",")) {
if (numberOfOpenBracketsEncountered==0) {
if (t.length()>0) res.add(t.trim());
t = "";
} else {
cur = cur;
t = t + cur;
}
} else {
cur = cur;
t = t + cur;
}
}
if (t.length()>0) res.add(t.trim());
return res;
}
public static void main(String[] args) {
System.out.println("Start tmpTest3");
List<String> inputs = new ArrayList<String>();
inputs.add("text2(text3, text4), text5(text6, text7)");
inputs.add("text2, text3(text4, text5(text6, text7))");
for (int c=0;c<inputs.size();c++) {
System.out.println("Running test for " + inputs.get(c));
List<String> res = process(inputs.get(c));
System.out.println("Got " + res.size() + " strings as a result:");
for (int d=0;d<res.size();d++) {
System.out.println(" - :" + res.get(d) + ":");
}
System.out.println("----------------------");
}
System.out.println("End tmpTest3");
}
}
答案 1 :(得分:0)
这会对你有用吗?
import java.util.Arrays;
class Program {
public static void main (String[] args) throws java.lang.Exception {
String subject1 = "text2(text3, text4), text5(text6, text7)";
String subject2 = "text2, text3(text4, text5(text6, text7))";
String p = "\\s*\\d*\\(\\)";
String[] res = subject1.split(p);
System.out.println(Arrays.toString(res));
res=subject2.split(p);
System.out.println(Arrays.toString(res));
} // end main
} // end
输出: - [text2(text3,text4),text5(text6,text7)] [text2,text3(text4,text5(text6,text7))]