Reputation: 2222
Assume that we have below string:
"test01,test02,test03,exceptional,case,test04"
What I want is to split the string into string array, like below:
["test01","test02","test03","exceptional,case","test04"]
How can I do that in Java?
Upvotes: 4
Views: 2485
Reputation: 73
String s1 = "test01.test02.test03.{i}.case.test04.test03.{i}.test03.{i}.test03.{i}";
String[] arr1 = s1.split("(?<!)\\.|\\.(?!\\{i})");
Output:
test01
test02
test03.{i}
case
test04
test03.{i}
test03.{i}
test03.{i}
Upvotes: 0
Reputation: 41838
Here's a dead-simple answer, don't know why I didn't think of it yesterday:
(?<!exceptional(?=,case)),
Explanation
A comma (the last character of the regex) that is not preceded by exceptional
followed by ,case
Upvotes: 0
Reputation: 785156
This negative lookaround regex should work for you:
(?<!exceptional),|,(?!case)
Java Code:
String[] arr = str.split("(?<!exceptional),|,(?!case)");
Explanation:
This regex matches a comma if any one of these 2 conditions meet:
exceptional
using negative lookbehind (?<!exceptional)
case
using negative lookahead (?!case)
That effectively disallows splitting on comma when it is surrounded by exceptional
and case
on either side.
Upvotes: 7
Reputation: 41838
@anubhava's answer is great—use it. For completion, here's a general solution that is applicable to many solutions and uses a beautifully simple regex:
exceptional,case|(,)
The left side of the alternation |
matches complete exceptional,case
. We will ignore these matches. The right side matches and captures commas to Group 1, and we know they are the right ones because they were not matched by the expression on the left. We then replace these commas by something distinctive, and split on that string.
This program shows how to use the regex (see the results at the bottom of the online demo):
String subject = "somethingelse,case,test02,test03,exceptional,case,test04,exceptional,notcase";
Pattern regex = Pattern.compile("exceptional,case|(,)");
Matcher m = regex.matcher(subject);
StringBuffer b= new StringBuffer();
while (m.find()) {
if(m.group(1) != null) m.appendReplacement(b, "@@SplitHere@@");
else m.appendReplacement(b, m.group(0));
}
m.appendTail(b);
String replaced = b.toString();
String[] splits = replaced.split("@@SplitHere@@");
for (String split : splits) System.out.println(split);
Reference
Upvotes: 1
Reputation: 7069
How can Java understand the exceptional,case
is a single word and not to split ?
Still If there would have been some other recurring character like ""
you could have split it.
For ex. if It was
"test01","test02","test03","exceptional,case","test04"
You could split it using ","
So in your case it is not possible, unless you use regular expression.
Upvotes: 0
Reputation: 326
You probably want to use split()
Like this:
String[] array = "test01,test02,test03,exceptional,case,test04".split(",");
Upvotes: -1