将具有由多个空格分隔的单词的行分开

时间:2013-08-19 08:29:35

标签: java regex split

我正在逐行解析一些文本文件,我需要拆分具有由多个空格分隔的单词的行。请建议我如何做到这一点

示例文本

John     is      working  in London

必需的输出

John 
is 
working
in London

4 个答案:

答案 0 :(得分:4)

使用\s{2,}匹配多个空格:

String text = "John     is      working  in London";
String[] words = text.split("\\s{2,}");
for (String word : words)
    System.out.println(word);

答案 1 :(得分:0)

这对你有用。 \1+将替换一个或多个空格。

 String str="John     is      working  in London";
       String[] arr=str.replaceAll("([\" \"])\\1+"," ").split(" ");
       for(String i:arr){
           System.out.println(i.trim());
       }

直播Demo

Out put

John
is
working
in
London

答案 2 :(得分:0)

试试这个简单的正则表达式:

String[] words = str.split("  +");

答案 3 :(得分:0)

您可以使用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