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

0

2 Answers 2

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());
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

small exeption: result: #p: [#ciccio:aaa, #caio: bbb, #ggg: [#fff:aaa] shuld be: #p: [#ciccio:aaa, #caio: bbb, #ggg: [#fff:aaa]]
this is correct: String regex = "(#[^,\[\]]+(?:\[.*?\]+)?)";
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.

3 Comments

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")
This is correct: String regex = "(#[^,\[\]]+(?:\[.*?\]+)?)";
That doesn't work for the following string though: "#sfondo: [#nome: 0, #imga: 0],#111: 222, #p: [#ciccio:aaa, #ggg: [#fff:aaa], #caio: bbb]"

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.