Reputation: 233
I'm reading in a file in Java and want to split each line by the value inside quotation marks. For example, a line would be...
"100","this, is","a","test"
I would like the array to look like..
[0] = 100
[1] = this, is
[2] = a
[3] = test
I normally split by comma, but since some of the fields include a comma (position 1 in the example above) it's not really suitable.
Thanks.
Upvotes: 6
Views: 3183
Reputation: 11776
You can do the following
String yourString = "\"100\",\"this, is\",\"a\",\"test\"";
String[] array = yourString.split(",\"");
for(int i = 0;i<array.length;i++)
array[i] = array[i].replaceAll("\"", "");
Finally array variable will be the desired array
Output:
100
this, is
a
test
Upvotes: 2
Reputation: 35011
Here's one simple way:
String example = "\"test1, test2\",\"test3\"";
int quote1, quote2 = -1;
while((quote2 != example.length() - 1) && quote1 = example.indexOf("\"", quote2 + 1) != -1) {
quote2 = example.indexOf("\"", quote1 + 1);
String sub = example.substring(quote1 + 1, quote2); // will be the text in your quotes
}
Upvotes: 2
Reputation: 16067
Here's a way using a regex.
public static void main (String[] args) {
String s = "\"100\",\"this, is\",\"a\",\"test\"";
String arr[] = s.split(Pattern.quote("\"\\w\"")));
System.out.println(Arrays.toString(arr));
}
Output:
["100","this, is","a","test"]
What it does is matches:
\" -> start by a "
\\w -> has a word character
\" -> finish by a "
I don't know what kind of values you have, but you can modify it as you need.
Upvotes: 1
Reputation: 2223
Quick and dirty, but works:
String s = "\"100\",\"this, is\",\"a\",\"test\"";
StringBuilder sb = new StringBuilder(s);
sb.deleteCharAt(0);
sb.deleteCharAt(sb.length()-1);
String [] buffer= sb.toString().split("\",\"");
for(String r : buffer)
System.out.println(r); code here
Upvotes: 0
Reputation: 48404
You can split it the following way:
String input = "\"100\",\"this, is\",\"a\",\"test\"";
for (String s:input.split("\"(,\")*")) {
System.out.println(s);
}
Output
100
this, is
a
test
Note The first array element will be empty.
Upvotes: 3