Reputation: 4294
I had an application in which my user input is to give the desired length of String elements separated by :
(colon)
My code to parse it is like this
String str[] = input.split(":");
But I am getting erroneous results when the user strings have : in between them.
I tried to use the string using \:
, but it never worked.
The sample user string may be like this 1:2:3
The expected value here is
str[0] = "1";
str[1] = "2";
str[2] = "3";
and is the same as actual
But if the String is like this 1:Title 1
: 2: Title 2
: 3: Title 3
The expected value here is
str[0] = "1: Title 1";
str[1] = "2: Title 2";
str[2] = "3: Title 3";
and is the not same as actual,
str[0] = "1";
str[1] = "Title 1";
str[2] = "2";
str[3] = "Title 2";
str[4] = "3";
str[5] = "Title 3";
How can I overcome this ?
Upvotes: 1
Views: 140
Reputation: 5151
The method String.split()
doesn't deal with the escaping automatically, and you should define it explicitly by yourself using regular expression. This question may help you.
Here is the snippet,
String input = "1\\:Title 1:2\\:Title 2:3\\:Title 3";
String[] strs = input.split("(?<!\\\\):");
for (String str : strs) {
System.out.println(str.replace("\\:", ":"));
}
Upvotes: 0
Reputation: 785561
Following should work for you:
String str = "1:Title 1 : 2: Title 2 : 3: Title 3";
String[] arr = str.split("\\s*:(?=\\s*\\d)\\s*");
System.out.printf("Split: %s%n", Arrays.toString(arr));
OUTPUT:
Split: [1:Title 1, 2: Title 2, 3: Title 3]
Upvotes: 0
Reputation: 109597
Use spaces around the splitting colon: split(" : ")
. This assumes that an ordinary colon in text will ordinarily not have a space in front.
Not much of an answer, but otherwise you'll need to specify some representation of a non-splitting colon, and handle it. For instance replace("\\:", "§")
and after splitting replace("§", ":")
.
Upvotes: 2