1

I have big prob with regular expressions in JAVA (spend 3 days!!!). this is my input string:

#sfondo: [#nome: 0, #imga: 0],#111: 222, #p: [#ciccio:aaa, #caio: bbb]

I need parse this string to array tree, must match like this:

group: #sfondo: [#nome: 0, #imga: 0]
group: #111: 222
group: #p: [#ciccio:aaa, #caio: bbb]

with or wythout nested brackets

I've tryed this:

"#(\\w+):(.*?[^,\]\[]+.*?),?"

but this group by each element separate with "," also inside brackets

Prince John Wesley
  • 62,492
  • 12
  • 87
  • 94

2 Answers2

3

Try this one:

import java.util.regex.*;

class Untitled {
  public static void main(String[] args) {
    String input = "#sfondo: [#nome: 0, #imga: 0],#111: 222, #p: [#ciccio:aaa, #caio: bbb]";
    String regex = "(#[^,\\[\\]]+(?:\\[.*?\\]+,?)?)";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);

    while (matcher.find()) {
      System.out.println("group: " + matcher.group());
    }
  }
}
ioseb
  • 16,625
  • 3
  • 33
  • 29
0

This seems to work for your example:

    String input = "#sfondo: [#nome: 0, #imga: 0],#111: 222, #p: [#ciccio:aaa, #caio: bbb]";
    String regex = "#\\w+: (\\[[^\\]]*\\]|[^\\[]+)(,|$)";
    Pattern p = Pattern.compile(regex);
    Matcher matcher = p.matcher(input);
    List<String> matches = new ArrayList<String>();
    while (matcher.find()) {
        String group = matcher.group();
        matches.add(group.replace(",", ""));
    }

EDIT:
This only works for a nested depth of one. There is no way to handle a nested structure of arbitrary depth with regex. See this answer for further explanation.

Community
  • 1
  • 1
Keppil
  • 45,603
  • 8
  • 97
  • 119
  • Thanks a lot.This work great but not with nested brackets like: "#sfondo: [#nome: 0, #imga: 0],#111: 222, #p: [#ciccio:aaa, #caio: bbb, #ggg: [#fff:aaa]]" (see: "#ggg") – Alberto Starosta Jun 14 '12 at 08:56
  • This is correct: String regex = "(#[^,\\[\\]]+(?:\\[.*?\\]+)?)"; – Alberto Starosta Jun 14 '12 at 09:09
  • That doesn't work for the following string though: "#sfondo: [#nome: 0, #imga: 0],#111: 222, #p: [#ciccio:aaa, #ggg: [#fff:aaa], #caio: bbb]" – Keppil Jun 14 '12 at 09:13