3

in Java, if I have a string with this format:

( string1 , string2 ) ( string2 ) ( string4 , string5 , string6 ) [s2]

How can I split the string to get an array of string as this?

string1 , string2
string2
string4 , string5 , string6
1
  • 2
    Do you want a single array of strings or an array of arrays of strings? Commented Nov 9, 2011 at 12:11

3 Answers 3

6

Try this:

    String test = "( string1 , string2 ) ( string2 ) ( string4 , string5 , string6 ) [s2]";

    String[] splits = test.split("\\(\\s*|\\)[^\\(]*\\(?\\s*");

    for (String split : splits) {
        System.out.println(split);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

+1 split() is a little simpler in concept, but I would either add in a bit to match any whitespace before the closing parentheses as well as after the opening ones, or remove the whitespace matching all together.
3

You can use a match :

List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("\\((.*?)\\)");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    matchList.add(regexMatcher.group(1));
} 

Matches anything between () and stores it into backreference 1.

Explanation :

 "\\(" +      // 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

Comments

0

You may want to use split on /\(.+?\)/ - something like this in 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.