除括号外的正则表达式,用于在管道之间分割

时间:2018-10-30 10:15:16

标签: java regex

我有以下文本行:

|random|[abc|www.abc.org]|1024|

我想用正则表达式将它们分为3部分

random
[abc|www.abc.org]
1024

当前,使用表达式\ |

可获得以下结果
random
[abc
www.abc.org]
1024

我的问题是我不能排除括号[]包围的中间列中的管道符号。

2 个答案:

答案 0 :(得分:2)

如果必须使用split,则可以使用正则表达式

\|(?=$|[^]]+\||\[[^]]+\]\|)

https://regex101.com/r/7OxmiY/1

它将与管道匹配,然后向前查找:

$,字符串的末尾,以便最后的|被分割,或者

[^]]+\|,非]字符,直到达到管道为止,确保[]内的管道不会被分割,或者

\[[^]]+\]\|-与上面相同,除了文字[]围绕模式

在Java中:

String input = "|random|[abc|www.abc.org]|[test]|1024|";
String[] output = input.split("\\|(?=$|[^]]+\\|)"); 

答案 1 :(得分:1)

您可以使用以下代码:

final String regex = "(?<=|)\\[?[\\w.]+\\|?[\\w.]+\\]?(?=|)";
final String string = "|random|[abc|www.abc.org]|[test]|1024|";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
}

输出:

Full match: random
Full match: [abc|www.abc.org]
Full match: [test]
Full match: 1024

请参见regex101:https://regex101.com/r/Fcb3Wx/1