Reputation: 17
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
Upvotes: 1
Views: 1608
Reputation: 46209
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.
Upvotes: 0
Reputation: 16951
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());
}
}
}
Upvotes: 3