Java Regex splits string between delimiter and keep delimiter

I have a java line that looks like this:

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

And I want to split this line into a delimiter (fname:jon)<here>(lname:doe).

I tried to split through regex \)\(, but it just breaks my code

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

Exit

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

I also examined this question: How to split a line, but also keep the delimiters? , but this did not help, because in my case I want to keep the separator )(and split the separator evenly, i.e. the first bracket should go to the first result and the second to the second result.

The regular expression that I used was s.split("(?<=\\)\\()"), and it returned the result:

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

This is my desired result:

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

, lookahead lookbehind :

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

DEMO

  • (?<=\)) lookbehind, , .
  • (?=\() lookahead, , .

(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);
+7

lookbehind :

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)
+7

Source: https://habr.com/ru/post/1015471/


All Articles