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)
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] .
split is faster, but complex separators which might involve look ahead, Regex is only option.
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.
You can split your string using positive lookahead and positive lookbehind like this:
RegEx (?<=\))(?=\()
DEMO
(?<=\))
positive lookbehind which indicates that closing bracket should preceed the split position.(?=\()
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With