1

I have a string like this:

String str = "[a,b,c,d],[1,2,3,4],[a,gf,d,cvb],[4,3,2,1]";

I want to split this string into four parts, like this:

[a,b,c,d]
[1,2,3,4]
[a,gf,d,cvb]
[4,3,2,1]

I tried this:

List<String> splitWords = Arrays.asList(str.split("\\],\\["));

When I use this, I get following strings:

[a,b,c,d
1,2,3,4
a,gf,d,cvb
4,3,2,1]

In this case, I also remove brackets next to commas, but I don't want to do that. What is the regex for my problem?

Tom
  • 16,842
  • 17
  • 45
  • 54
nope
  • 751
  • 2
  • 12
  • 29

2 Answers2

0

Try this:

    List<String> splitWords = Arrays.asList(str.split("],"));
    for(int i = 0; i < splitWords.size()-1; i++)
        splitWords.set(i, splitWords.get(i) + "]");
granmirupa
  • 2,780
  • 16
  • 27
0

this regex can do what you are looking for:

"[(.*?)]"

Example:

String str = "[a,b,c,d],[1,2,3,4],[a,gf,d,cvb],[4,3,2,1]";
Pattern logEntry = Pattern.compile("\\[(.*?)\\]");
Matcher matchPattern = logEntry.matcher(str);
while (matchPattern.find()) {
    System.out.println("[" + matchPattern.group(1) + "]");
}

that will print:

[a,b,c,d]

[1,2,3,4]

[a,gf,d,cvb]

[4,3,2,1]

which is what you are looking for...

Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97