使用任意数量的逗号和空格拆分字符串 [英] Split a string with arbitrary number of commas and spaces
本文介绍了使用任意数量的逗号和空格拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串我正试图变成一个列表,但我得到空条目。
I have a String that I'm trying to turn into a list but I get empty entries.
",A,B,C,D, ,,,"
returns
[, A, B, C, D, , , ,]
我想删除所有空逗号:
[A, B, C, D]
我正在尝试
current.split(",+\\s?")
,它不会产生我想要的结果。我应该使用什么正则表达式?
which does not produce the result I want. What regex should I use instead?
推荐答案
您需要两个步骤,但只需要一行:
You need two steps, but only one line:
String[] values = input.replaceAll("^[,\\s]+", "").split("[,\\s]+");
调用 replaceAll()
删除行距分隔符。
分割是在任意数量的分隔符上完成的。
The call to replaceAll()
removes leading separators.
The split is done on any number of separators.
split()$ c的行为$ c>表示忽略尾随空白值,因此在拆分之前不需要修剪尾随分隔符。
The behaviour of split()
means that a trailing blank value is ignored, so no need to trim trailing separators before splitting.
这是一个测试:
public static void main(String[] args) throws Exception {
String input = ",A,B,C,D, ,,,";
String[] values = input.replaceAll("^[,\\s]+", "").split("[,\\s]+");
System.out.println(Arrays.toString(values));
}
输出:
[A, B, C, D]
这篇关于使用任意数量的逗号和空格拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文