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

时间:2021-12-17 21:39:28

I am parsing some text files line by line, my need is to split the lines which have words separated by more than one white space. please suggest me how to do this

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

sample text

John     is      working  in London

required output

John 
is 
working
in London

4 个解决方案

#1


4  

Use \s{2,} to match multiple spaces:

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

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

#2


0  

This will work for you. \1+ will replace one or more white spaces.

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

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

Live Demo

Out put

John
is
working
in
London

#3


0  

Try this simple regex:

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

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

#4


0  

You can use the java.util.StringTokenizer class.

您可以使用java.util.StringTokenizer类。

StringTokenizer st = new StringTokenizer("John     is      working  in London"," ",false);
while (st.hasMoreElements()) {
        System.out.println("StringTokenizer Output: " + st.nextElement());
    }

Output:

John
is
working
in
London

#1


4  

Use \s{2,} to match multiple spaces:

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

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

#2


0  

This will work for you. \1+ will replace one or more white spaces.

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

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

Live Demo

Out put

John
is
working
in
London

#3


0  

Try this simple regex:

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

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

#4


0  

You can use the java.util.StringTokenizer class.

您可以使用java.util.StringTokenizer类。

StringTokenizer st = new StringTokenizer("John     is      working  in London"," ",false);
while (st.hasMoreElements()) {
        System.out.println("StringTokenizer Output: " + st.nextElement());
    }

Output:

John
is
working
in
London