我正在逐行解析一些文本文件,我的需要是拆分包含多个空格分隔的单词的行。请建议我如何做到这一点
示例文本
John is working in London
所需输出
John
is
working
in London
用于\s{2,}
匹配多个空格:
String text = "John is working in London";
String[] words = text.split("\\s{2,}");
for (String word : words)
System.out.println(word);
您可以使用 java.util.StringTokenizer 类。
StringTokenizer st = new StringTokenizer("John is working in London"," ",false);
while (st.hasMoreElements()) {
System.out.println("StringTokenizer Output: " + st.nextElement());
}
输出:
John
is
working
in
London
试试这个简单的正则表达式:
String[] words = str.split(" +");
这对你有用。\1+
将替换一个或多个空格。
String str="John is working in London";
String[] arr=str.replaceAll("([\" \"])\\1+"," ").split(" ");
for(String i:arr){
System.out.println(i.trim());
}
现场演示
输出
John
is
working
in
London