在Java中的多个空格处使用tokenizer或split string

时间:2011-10-06 19:12:44

标签: java string tokenize

我需要将字符串标记为有多个空格。

例如

"HUNTSVILLE, AL                   30   39.8   44.3   52.3"

成为

"HUNTSVILLE, AL","30","39.8","44.3","52.3"


StringTokenizer st = new StringTokenizer(str, "   ");

只是标记任何空格,我无法找出正则表达式来做我需要的。

由于

4 个答案:

答案 0 :(得分:8)

试试这个:

String s = "HUNTSVILLE, AL                   30   39.8   44.3   52.3";
String[] parts = s.split("\\s{3,}");
for(String p : parts) {
  System.out.println(p);
}

\s匹配任何空白字符,{3,}将匹配3次或更多次。

上面的代码段会打印出来:

HUNTSVILLE, AL
30
39.8
44.3
52.3

答案 1 :(得分:3)

你不能使用拆分吗?

String[] tokens = string.split("  ");

您必须过滤空条目。

答案 2 :(得分:3)

尝试这种方式:

String[] result = "HUNTSVILLE, AL                   30   39.8   44.3   52.3".split("[ ]{2,}");
     for (int x=0; x<result.length; x++)
         System.out.println(result[x]);

[] - 代表空间
{2,} - 代表超过2

答案 3 :(得分:2)

 /*
 * Uses split to break up a string of input separated by
 * whitespace.
 */
import java.util.regex.*;

public class Splitter {
    public static void main(String[] args) throws Exception {
        // Create a pattern to match breaks
        Pattern p = Pattern.compile("[ ]{2,}");
        // Split input with the pattern
        String[] result = 
                 p.split("one,two, three   four ,  five");
        for (int i=0; i<result.length; i++)
            System.out.println(result[i]);
    }
}
相关问题