Splitting string by value between quotes in Java

I am reading in a file in Java and want to split each line by the value inside the quotes. For example, the line would be ...

"100", "this, is", "a", "test"

I would like the array to look like this.

[0] = 100 [1] = this, is [2] = a [3] = test 

I usually separate the comma, but since some of the fields include a comma (position 1 in the example above), it does not fit.

Thanks.

+6
source share
5 answers

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, the array variable will be the desired array

Output:

  100 this, is a test 
+2
source

Here is 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 } 
+2
source

You can break it as follows:

 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 element of the array will be empty.

+2
source

Quick and dirty, but it 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 
0
source

Here, a regular expression method is used.

 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 he does is coincidences:

  \" -> start by a " \\w -> has a word character \" -> finish by a " 

I do not know what values ​​you have, but you can change it as necessary.

0
source

Source: https://habr.com/ru/post/977132/


All Articles