我想在标点符号和空格中拆分字符串,但保留标点符号。防爆
String example = "How are you? I am fine!"
我想要有一个结果
["How","are","you","?","I","am","fine","!"]
但是我得到了
["how"," ","are"," ","you"," ","?"," ","i"," ","am"," ","fine"," ","!"].
我用的是 example.toLowerCase().trim().split("(?<=\\b|[^\\p{L}])");
你为什么要这么做toLowerCase()
?这已经弄乱了您的预期结果。以及为什么trim()
在完整字符串上?
只需一个split
电话即可完成操作。
一种替代方法是只过滤掉不需要的条目:
String example = "How are you? I am fine!";
Pattern pattern = Pattern.compile("\\b");
String[] result = pattern.splitAsStream(example)
.filter(Predicate.not(String::isBlank))
.toArray(String[]::new);
System.out.println(Arrays.toString(result));
输出:
[How, are, you, ? , I, am, fine, !]
对您希望[How,are,you,?,I,am,fine,!]
作为输出的评论作出反应;只是不打印,Arrays.toString
而是自己手动构建字符串。该数组不包含任何空格。
System.out.println("[" + String.join(",", result) + "]");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句