简体   繁体   中英

Java regular expression nested

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

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());
    }
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM