,如果我有一个这种格式的字符串:
( string1 , string2 ) ( string2 ) ( string4 , string5 , string6 ) [s2]
如何拆分字符串以获取字符串数组?
string1 , string2
string2
string4 , string5 , string6
答案 0 :(得分:6)
试试这个:
String test = "( string1 , string2 ) ( string2 ) ( string4 , string5 , string6 ) [s2]";
String[] splits = test.split("\\(\\s*|\\)[^\\(]*\\(?\\s*");
for (String split : splits) {
System.out.println(split);
}
答案 1 :(得分:3)
您可以使用匹配:
List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("\\((.*?)\\)");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group(1));
}
匹配()之间的任何内容并将其存储到反向引用1中。
说明:
"\\(" + // Match the character “(” literally
"(" + // Match the regular expression below and capture its match into backreference number 1
"." + // Match any single character that is not a line break character
"*?" + // Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
")" +
"\\)" // Match the character “)” literally
答案 2 :(得分:0)
您可能希望在/\(.+?\)/
上使用拆分 - 在java中使用这样的东西:
Pattern p = Pattern.compile("\\(.+?\\)");
Matcher m = p.matcher(myString);
ArrayList<String> ar = new ArrayList<String>();
while (m.find()) {
ar.add(m.group());
}
String[] result = new String[ar.size()];
result = ar.toArray(result);