匹配方括号内的内容,包括嵌套的方括号

时间:2015-10-17 15:07:54

标签: java regex

我正在尝试编写一个剧透识别系统,以便字符串中的任何破坏者都被指定的扰流角色替换。

我想匹配方括号包围的字符串,这样方括号内的内容就是捕获组1,包含周围括号的整个字符串就是匹配。

我目前正在使用\[(.*?]*)\],稍微修改了此答案here中的表达式,因为我还希望嵌套的方括号成为捕获组1的一部分。

该表达式的问题在于,虽然它可以工作并匹配以下内容:

  • Jim ate a [sandwich][sandwich]sandwich匹配为第1组
  • Jim ate a [sandwich with [pickles and onions]][sandwich with [pickles and onions]]sandwich with [pickles and onions]匹配为第1组
  • [[[[][[[[][[[匹配为第1组
  • []]]][]]]]]]]匹配为第1组

但是,如果我想匹配以下内容,则无法按预期工作:

  • Jim ate a [sandwich with [pickles] and [onions]]匹配两者:
    • [sandwich with [pickles]sandwich with [pickles作为第1组
    • [onions]]onions]作为第1组

我应该使用哪种表达方式,使[sandwich with [pickles] and [onions]]sandwich with [pickles] and [onions]作为第1组匹配?

修改

由于使用正则表达式在Java中实现这一点似乎是不可能的,还有其他解决方案吗?

编辑2

我还希望能够通过找到的每个匹配来拆分字符串,因此由于String.split(regex)方便,因此更难实现正则表达式的替代方法。这是一个例子:

  • Jim ate a [sandwich] with [pickles] and [dried [onions]]匹配所有:
    • [sandwich]sandwich作为第1组
    • [pickles]pickles作为第1组
    • [dried [onions]]dried [onions]作为第1组

分句应该如下:

Jim ate a
with
and

1 个答案:

答案 0 :(得分:2)

更直接的解决方案

This solution将省略空的或仅空白的子串

public static List<String> getStrsBetweenBalancedSubstrings(String s, Character markStart, Character markEnd) {
    List<String> subTreeList = new ArrayList<String>();
    int level = 0;
    int lastCloseBracket= 0;
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
            if (c == markStart) {
                    level++;
                    if (level == 1 && i != 0 && i!=lastCloseBracket &&
                        !s.substring(lastCloseBracket, i).trim().isEmpty()) {
                            subTreeList.add(s.substring(lastCloseBracket, i).trim());
                }
            }
        } else if (c == markEnd) {
            if (level > 0) { 
                level--;
                lastCloseBracket = i+1;
            }
            }
    }
    if (lastCloseBracket != s.length() && !s.substring(lastCloseBracket).trim().isEmpty()) {
        subTreeList.add(s.substring(lastCloseBracket).trim());  
    }
    return subTreeList;
}

然后,将其用作

String input = "Jim ate a [sandwich][ooh] with [pickles] and [dried [onions]] and ] [an[other] match] and more here";
List<String> between_balanced =  getStrsBetweenBalancedSubstrings(input, '[', ']');
System.out.println("Result: " + between_balanced);
// => Result: [Jim ate a, with, and, and ], and more here]

原始答案(更复杂,显示了提取嵌套括号的方法)

您还可以提取平衡括号内的所有子串,然后用它们分开:

String input = "Jim ate a [sandwich] with [pickles] and [dried [onions]] and ] [an[other] match]";
List<String> balanced = getBalancedSubstrings(input, '[', ']', true);
System.out.println("Balanced ones: " + balanced);
List<String> rx_split = new ArrayList<String>();
for (String item : balanced) {
    rx_split.add("\\s*" + Pattern.quote(item) + "\\s*");
}
String rx = String.join("|", rx_split);
System.out.println("In-betweens: " + Arrays.toString(input.split(rx)));

此函数将找到所有[] - 平衡子串:

public static List<String> getBalancedSubstrings(String s, Character markStart, 
                                     Character markEnd, Boolean includeMarkers) {
    List<String> subTreeList = new ArrayList<String>();
    int level = 0;
    int lastOpenBracket = -1;
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c == markStart) {
            level++;
            if (level == 1) {
                lastOpenBracket = (includeMarkers ? i : i + 1);
            }
        }
        else if (c == markEnd) {
            if (level == 1) {
                subTreeList.add(s.substring(lastOpenBracket, (includeMarkers ? i + 1 : i)));
            }
            if (level > 0) level--;
        }
    }
    return subTreeList;
}

请参阅IDEONE demo

代码执行结果:

Balanced ones: ['[sandwich], [pickles], [dried [onions]]', '[an[other] match]']
In-betweens: ['Jim ate a', 'with', 'and', 'and ]']

致谢:getBalancedSubstrings基于peter.murray.rustHow to split this “Tree-like” string in Java regex? post答案。