使用split函数分隔CSV文件并忽略引号。

huangapple go评论86阅读模式
英文:

Separating CSV file with split function and IGNORING quotes

问题

String str = "\"10\",\"100\",\"11\",\"1\"";
String[] tokens = str.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
英文:

I have this string from a csv file = "10","100","11","1"
and i would like to split it on Java into an array like this:

10,100,11,1

I've been using this piece of code for that but i need to add a part to "Not include quotes", is that
possible? if not, how could i easily get just the integer values from it?

String str = "\"10\",\"100\",\"11\",\"1\"";
String[] tokens = str.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);

Any help would be appreciated. Thank you!

答案1

得分: 3

如果您愿意使用不需要正则表达式而是使用流API的解决方案,您可以简单地通过逗号对String进行split,对结果进行流处理,去除每个项周围的双引号并解析为int

public static void main(String[] args) {
    String str = "\"10\",\"100\",\"11\",\"1\"";
    // 对逗号分隔的结果进行流处理
    List<Integer> numbers = Arrays.stream(str.split(","))
                                    // 去除双引号并解析为int
                                    .map(s -> Integer.parseInt(s.replace("\"", "")))
                                    // 返回一个整数列表
                                    .collect(Collectors.toList());
    // 然后打印整数
    numbers.forEach(System.out::println);
}

这将输出:

10
100
11
1

作为另一种选择,您还可以创建一个int[]而不是List<Integer>,以下是如何实现(输出与上述相同):

public static void main(String[] args) {
    String str = "\"10\",\"100\",\"11\",\"1\"";
    // 对逗号分隔的结果进行流处理
    int[] numbers = Arrays.stream(str.split(","))
                            // 去除双引号并解析为int
                            .mapToInt(s -> Integer.parseInt(s.replace("\"", "")))
                            // 转换为数组
                            .toArray();
    // 然后打印整数
    Arrays.stream(numbers).forEach(System.out::println);
}
英文:

If you are willing to use a solution that does not need a regular expression but uses the stream API instead, you could just split the String by comma, stream the results, remove the double quotes around each item and parse it to an int:

public static void main(String[] args) {
	String str = &quot;\&quot;10\&quot;,\&quot;100\&quot;,\&quot;11\&quot;,\&quot;1\&quot;&quot;;
	// stream the results of splitting by comma
	List&lt;Integer&gt; numbers = Arrays.stream(str.split(&quot;,&quot;))
								// parse the int after remov&#237;ng the double-quotes
								.map(s -&gt; Integer.parseInt(s.replace(&quot;\&quot;&quot;, &quot;&quot;)))
								// and return a list of integers
								.collect(Collectors.toList());
	// then print the integers
	numbers.forEach(System.out::println);
}

This outputs

10
100
11
1

As an alternative, you could also create an int[] instead of a List&lt;Integer&gt;, here's how to do that (with the same output as shown above):

public static void main(String[] args) {
	String str = &quot;\&quot;10\&quot;,\&quot;100\&quot;,\&quot;11\&quot;,\&quot;1\&quot;&quot;;
	// stream the results of splitting by comma
	int[] numbers = Arrays.stream(str.split(&quot;,&quot;))
								// parse and map to int after remov&#237;ng the double-quotes
								.mapToInt(s -&gt; Integer.parseInt(s.replace(&quot;\&quot;&quot;, &quot;&quot;)))
								// and make it an array
								.toArray();
	// then print the integers
	Arrays.stream(numbers).forEach(System.out::println);
}

答案2

得分: 2

你可以简单地通过以下方式获取 String[]

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String str = "\"10\",\"100\",\"11\",\"1\"";

        // Replace double quote with blank
        str = str.replace("\"", "");

        // Split the resulting string on comma
        String[] arr = str.split(",");

        // Display the resulting array
        System.out.println(Arrays.toString(arr));
    }
}

输出:

[10, 100, 11, 1]

**或者,**你也可以选择以下替代方法:

import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String str = "\"10\",\"100\",\"11\",\"1\"";
        List<Integer> list = Pattern.compile("\\d+")
                                    .matcher(str)
                                    .results()
                                    .map(MatchResult::group)
                                    .map(Integer::valueOf)
                                    .collect(Collectors.toList());

        System.out.println(list);
    }
}

注意,替代方法返回的是 List<Integer>。如果你需要 List<String>,只需从其中移除 .map(Integer::valueOf) 部分。

英文:

You can get String[] simply as follows:

import java.util.Arrays;

public class Main {
	public static void main(String[] args) {
		String str = &quot;\&quot;10\&quot;,\&quot;100\&quot;,\&quot;11\&quot;,\&quot;1\&quot;&quot;;

		// Replace double quote with blank
		str = str.replace(&quot;\&quot;&quot;, &quot;&quot;);

		// Split the resulting string on comma
		String[] arr = str.split(&quot;,&quot;);

		// Display the resulting array
		System.out.println(Arrays.toString(arr));
	}
}

Output:

[10, 100, 11, 1]

Alternatively,

import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Main {
	public static void main(String[] args) {
		String str = &quot;\&quot;10\&quot;,\&quot;100\&quot;,\&quot;11\&quot;,\&quot;1\&quot;&quot;;
		List&lt;Integer&gt; list=Pattern.compile(&quot;\\d+&quot;)
					      .matcher(str)
					      .results()
					      .map(MatchResult::group)
					      .map(Integer::valueOf)
					      .collect(Collectors.toList());
		
		System.out.println(list);
	}
}

Note that the alternative solution returns List&lt;Integer&gt;. If you need List&lt;String&gt; remove .map(Integer::valueOf) from it.

答案3

得分: 0

请尝试这样写,

String str = "\"10\",\"100\",\"11\",\"1\"";

String[] arr = str.replaceAll("^(\"|\"$)","").split("\",\"");

System.out.println(Arrays.toString(arr));
英文:

Try this,

String str = &quot;\&quot;10\&quot;,\&quot;100\&quot;,\&quot;11\&quot;,\&quot;1\&quot;&quot;;

String[] arr = str.replaceAll(&quot;(^\&quot;|\&quot;$)&quot;,&quot;&quot;).split(&quot;\&quot;,\&quot;&quot;);

System.out.println(Arrays.toString(arr));

huangapple
  • 本文由 发表于 2020年8月31日 22:10:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63672415.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定