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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With