在 java 中使用","但不", "拆分字符串



我有一个这样的字符串:

123,TV,August 14, 2020,"This is a fantasy series, and top rated"

我在这个问题上使用了String.split((,但我的分隔符应该只基于逗号分隔字符串,没有尾随空格。

预期输出

["123","TV","August 14, 2020","This is a fantasy series, and top rated"]

实际输出

["123","TV","August 14"," 2020","This is a fantasy series", " and top rated"]

它是在考虑所有逗号的情况下拆分字符串。我只想考虑没有尾随空格或双引号的逗号("(。

有人能给我建议吗?

您可以与Negative Lookahead(?!s)组合以断言逗号后面没有空格

String s = "123,TV,August 14, 2020 ,"This is a fantasy series, and top rated"";
List<String> parts = Arrays.stream(s.split(",(?!\s)"))
.map(x -> x.replaceAll("^["\s]|["\s]$", ""))
.collect(Collectors.toList());
for (String p : parts) {
System.out.println(">>" + p + "<<");
}
>>123<<
>>TV<<
>>August 14, 2020<<
>>This is a fantasy series, and top rated<<

相关内容

  • 没有找到相关文章

最新更新