我在 JAVA 中使用正则表达式有很大的概率(花 3 天!!)。这是我的输入字符串:
#sfondo: [#nome: 0, #imga: 0],#111: 222, #p: [#ciccio:aaa, #caio: bbb]
我需要将此字符串解析为数组树,必须像这样匹配:
group: #sfondo: [#nome: 0, #imga: 0]
group: #111: 222
group: #p: [#ciccio:aaa, #caio: bbb]
带或带嵌套括号
我试过这个:
"#(\w+):(.*?[^,][]+.*?),?"
但是这个组由每个元素分开,","也在括号内
试试这个:
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());
}
}
}
这似乎适用于您的示例:
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(",", ""));
}
编辑:
这仅适用于嵌套深度为 1。没有办法用正则表达式处理任意深度的嵌套结构。有关进一步说明,请参阅此答案。