Java分割字符串

3
在Java中,如果我有一个格式为以下内容的字符串:
( string1 , string2 ) ( string2 ) ( string4 , string5 , string6 ) [s2]

我该如何分割字符串以得到以下的字符串数组?
string1 , string2
string2
string4 , string5 , string6

2
你需要一个字符串的单一数组还是一个字符串的多维数组? - Daan
3个回答

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 split()在概念上要简单一些,但我会添加一点内容来匹配括号闭合前后的任何空格,或者完全删除所有空格匹配。 - Code Jockey

3
您可以使用“匹配”:
List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("\\((.*?)\\)");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    matchList.add(regexMatcher.group(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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接