Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java split string

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
like image 389
Safari Avatar asked Aug 30 '26 21:08

Safari


2 Answers

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);
    }
like image 173
Francisco Paulo Avatar answered Sep 02 '26 11:09

Francisco Paulo


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
like image 43
FailedDev Avatar answered Sep 02 '26 10:09

FailedDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!