[英]How to split a String with two delimiters and keep only one of of them?
我想在标点符号和空格中拆分字符串,但保留标点符号。 前任
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) + "]");
你可以这样做:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String example = "How are you? I am fine!";
String[] arr = example.split("\\s+|\\b(?=\\p{Punct})");
System.out.println(Arrays.toString(arr));
}
}
输出:
[How, are, you, ?, I, am, fine, !]
正则表达式的解释:
\\\\s+
指定空格\\\\b
指定单词边界(?=\\\\p{Punct})
指定标点符号的正面展望。|
指定交替 ( OR
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.