Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我的输入字符串是
String s = ",1,,2, ,3,4,5,,6"; String[] array = s.split(","); System.out.println(Arrays.toString(array));
现在我得到这个输出
[, 1, , 2, , 3, 4, 5, , 6]
但预期的输出是
[1, 2, 3, 4, 5, 6]
使用这个增强的正则表达式来避免空匹配:
s.replaceFirst("^( *, *)+", "").split("(, *)+"); //=> [1, 2, 3, 4, 5, 6]
尝试这个
s.replaceAll("^[, ]+", "").split("[, ]+");
我会分担任务。首先,您需要修剪开头或结尾的所有逗号。
之后,您可以使用拆分字符串\s*,[,\s]*
\s*,[,\s]*