簡體   English   中英

在Java中的多個空格處使用tokenizer或split string

[英]tokenizer or split string at multiple spaces in java

我需要標記一個字符串,其中有多個空格。

例如

"HUNTSVILLE, AL                   30   39.8   44.3   52.3"

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


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

只是標記任何空格,我無法弄清楚正則表達式做我需要的。

謝謝

嘗試這個:

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匹配任何空格char, {3,}將匹配3次或更多次。

上面的代碼段會打印出來:

HUNTSVILLE, AL
30
39.8
44.3
52.3

你不能用拆分嗎?

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

您必須過濾空條目。

試試這種方式:

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個

 /*
 * 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]);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM