Java Regex在分隔符和保持分隔符之间拆分字符串

时间:2017-03-04 13:19:17

标签: java arrays regex string

我有一个看起来像这样的java字符串;

(fname:jon)(lname:doe)(guaranteer: Sam (W) Willis)(age:35)(addr:1 Turnpike Plaza)(favcolor:blue)

我想将此字符串与分隔符(fname:jon)<here>(lname:doe)分开。

我尝试拆分正则表达式\)\(,但它只是破坏了我的代码

arr = s.split("\\)\\(");
for (String a: arr) System.out.println(a);

输出

(fname:jon
lname:doe
guaranteer: Sam (W) Willis
age:35
addr:1 Turnpike Plaza
favcolor:blue)

我也看过这个问题:How to split a string, but also keep the delimiters?,但它没有帮助,因为在我的情况下,我想保持分隔符)(和分割分隔符,即第一个括号应该是第一个结果,第二个是第二个结果。

我使用的正则表达式是s.split("(?<=\\)\\()")并且它给出了输出:

(fname:jon)(
lname:doe)(
guaranteer: Sam (W) Willis)(
age:35)(
addr:1 Turnpike Plaza)(
favcolor:blue)

这是我想要的输出:

(fname:jon)
(lname:doe)
(guaranteer: Sam (W) Willis)
(age:35)
(addr:1 Turnpike Plaza)
(favcolor:blue)

2 个答案:

答案 0 :(得分:8)

你可以使用正向前瞻和正面观察分割你的字符串,如下所示:

RegEx (?<=\))(?=\()

DEMO

  1. (?<=\))正向后观,表示结束括号应位于分割位置之前。
  2. (?=\()正向前瞻,表示开括号应该遵循该分割位置。
  3. <强>输出

    (fname:jon)
    (lname:doe)
    (guaranteer: Sam (W) Willis)
    (age:35)
    (addr:1 Turnpike Plaza)
    (favcolor:blue)
    

    <强>代码

    String s = "(fname:jon)(lname:doe)(guaranteer: Sam (W) Willis)(age:35)(addr:1 Turnpike Plaza)(favcolor:blue)";
    String arr[] = s.split("(?<=\\))(?=\\()");
    for (String a: arr) System.out.println(a);
    

答案 1 :(得分:7)

您可以使用正向后视否定前瞻来实现此目标:

public static void main(String[] args) throws Exception {
    String s = "(fname:jon)(lname:doe)(guaranteer: Sam (W) Willis)(age:35)"
            + "(addr:1 Turnpike Plaza)(favcolor:blue)";
    String[] arr = s.split("(?<=\\)(?!\\s))"); // positive lookbehind for ")" and negative lookahead for "space"
    for (String str : arr) {
        System.out.println(str);
    }

}

O / P:

(fname:jon)
(lname:doe)
(guaranteer: Sam (W) Willis)
(age:35)
(addr:1 Turnpike Plaza)
(favcolor:blue)