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