0

I have a String which is formatted as such

[dgdds,dfse][fsefsf,sefs][fsfs,fsef]

How would I use Regex to quickly parse this to return an ArrayList with each value containing one "entry" as such?

ArrayList <String>:

0(String): [dgdds,dfse]

1(String): [fsefsf,sefs]

2(String): [fsfs,fsef]

Really stuck with this, any help would be great.

7 Answers 7

3

How about

String myData = "[dgdds,dfse][fsefsf,sefs][fsfs,fsef]";
List<String> list = new ArrayList<>(Arrays.asList(myData
        .split("(?<=\\])")));

for (String s : list)
    System.out.println(s);

Output:

[dgdds,dfse]
[fsefsf,sefs]
[fsfs,fsef]

This regex will use look behind mechanism to split on each place after ].

Sign up to request clarification or add additional context in comments.

Comments

3

You should try this regex :
Pattern pattern = Pattern.compile("\\[\\w*,\\w*\\]");

Comments

2

Old, easy, awesome way :)

String s = "[dgdds,dfse][fsefsf,sefs][fsfs,fsef]";
        String[] token = s.split("]");
        for (String string : token) {
            System.out.println(string + "]");
        }

Comments

1

You can use simple \[.*?\] regex, which means: match a string starting with [, later zero or more characters (but as short as possible, not greedly, that's why the ? in .*?), ending with ].

This works, you can test it on Ideone:

List<String> result = new ArrayList<String>();
String input = "[dgdds,dfse][fsefsf,sefs][fsfs,fsef]";
Pattern pattern = Pattern.compile("\\[.*?\\]");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) 
{
    result.add(matcher.group());
}
System.out.println(result);

Output:

[[dgdds,dfse], [fsefsf,sefs], [fsfs,fsef]]

Comments

1

You may need to do it in two passes:

(1) Split out by the brackets if it's just a 1D array (not clear in the question):

String s = "[dgdds,dfse][fsefsf,sefs][fsfs,fsef]";
String[] sArray = s.split("\\[|\\]\\[|\\]");

(2) Split by the commas if you want to also divide, say "dgdds,dfse"

sArray[i].split(",");

Comments

1

We can use split(regex) function directly by escaping "]": "\\]" and then use it as the regex for pattern matching:

String str = "[dgdds,dfse][fsefsf,sefs][fsfs,fsef]";
     String bal[] = str.split("\\]");

     ArrayList<String>finalList = new ArrayList<>();

     for(String s:bal)
     {
         finalList.add(s+"]");
     }
     System.out.println(finalList);

Comments

1

Split using this (?:(?<=\])|^)(?=\[) might work if there are nothing between ][

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.