Reputation: 37
The value ALL||test > test's done> test's done again's done||test > test's done> test's done again's done 2 is an array list
what i want to do is have a list separated by ||
so the first element is :
ALL
second:
test > test's done> test's done again's done
last:
test > test's done> test's done again's done 2
code i wrote:
String record1 = record.toString();
String[] parts = record1.split("||");
for (int i = 1; i <= parts.length; i++) {
System.out.println(parts[i]);
}
What i'm getting is each letter by itself and at the end a ]
character which is unwanted as well.
Upvotes: 1
Views: 61
Reputation: 79425
|
is a metacharacter and therefore, you need to escape it using a \
. Since \
itself is a metacharacter, you need another \
to escape the \
. Thus, you need to use \\|\\|
as the regex.
public class Main {
public static void main(String[] args) {
String[] parts = "ALL||test > test's done> test's done again's done||test > test's done> test's done again's done 2"
.split("\\|\\|");
for (String s : parts) {
System.out.println(s);
}
}
}
Output:
ALL
test > test's done> test's done again's done
test > test's done> test's done again's done 2
Another problem with your code is that the range of your loop counter is 1 to length_of_ the_array
whereas the indices of a Java array are in the range of 0 to (length_of_ the_array - 1)
. Therefore, if you want to access the elements of the array using their indices, your code should be:
for (int i = 0; i < parts.length; i++) {
System.out.println(parts[i]);
}
Upvotes: 0
Reputation: 159
You can split by using the following code:
String [] parts = record1.split("\\|\\|");
Also, the code written above won't work as the loop is running from 1 to parts.length instead of 0 to parts.length-1.
Upvotes: 1