Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex split string between delimiter and keep delimiter [duplicate]

I have a java string 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 String from delimiter (fname:jon)<here>(lname:doe).

I tried splitting through regex \)\( but it just breaks my code

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

Output

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

I also looked at this question: How to split a string, but also keep the delimiters?, but it didn't helped because in my case, I want to keep the delimiter )( and split delimiter evenly as well, i.e., the first bracket should go to first result and second to second result.

The regex that i used was s.split("(?<=\\)\\()") and it gave output:

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

This is my desired output:

(fname:jon)
(lname:doe)
(guaranteer: Sam (W) Willis)
(age:35)
(addr:1 Turnpike Plaza)
(favcolor:blue)
like image 250
Cupid Avatar asked Mar 04 '17 13:03

Cupid


People also ask

How do you split a string but keep the delimiters?

Summary: To split a string and keep the delimiters/separators you can use one of the following methods: Use a regex module and the split() method along with \W special character. Use a regex module and the split() method along with a negative character set [^a-zA-Z0-9] .

Is regex faster than string split?

split is faster, but complex separators which might involve look ahead, Regex is only option.

Can we split string using regex?

Split(String) Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.


1 Answers

You can split your string using positive lookahead and positive lookbehind like this:

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

DEMO

  1. (?<=\)) positive lookbehind which indicates that closing bracket should preceed the split position.
  2. (?=\() positive lookahead which indicates that opening bracket should follow that split position.

Output

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

Code

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);
like image 75
Raman Sahasi Avatar answered Nov 15 '22 13:11

Raman Sahasi