使用delimiters-Java拆分字符串

时间:2012-07-31 12:17:46

标签: java regex string split

我有一个字符串,我想分开分割值。

例如,我想拆分以下字符串:

            Test1 Avg. running Time: 66,3 [ms], (Ref: 424.0) ===> Well done, It is 80% faster

我会分别想要66,3 [ms]和Ref值。

如果你们中的任何人能够建议我哪种方式能够做到这一点,那将会很有帮助。

我应该使用分隔符(:)吗?但在这种情况下,我收到输出

            66,3 [ms], (Ref: 424.0) ===> Well done, It is 80% faster 

或者我应该使用'正则表达式'?

4 个答案:

答案 0 :(得分:1)

对于这种情况,你可以使用.split(", ");因为','除了数字之外有空白。

还可以在 this post 中查看现成的解析器。

答案 1 :(得分:0)

您可以使用split()功能...

String s = "66,3 [ms], (Ref: 424.0) ===> Well done, It is 80% faster";

String[] arr = s.split(", ");

答案 2 :(得分:0)

使用这种方式

public class JavaStringSplitExample {

    public static void main(String args[]) {

        String str = "one-two-three";
        String[] temp;

        String delimiter = "-";

        temp = str.split(delimiter);

        for (int i = 0; i < temp.length; i++)
            System.out.println(temp[i]);

        /*
         * NOTE : Some special characters need to be escaped while providing
         * them as delimiters like "." and "|".
         */

        System.out.println("");
        str = "one.two.three";
        delimiter = "\\.";
        temp = str.split(delimiter);
        for (int i = 0; i < temp.length; i++)
            System.out.println(temp[i]);

        /*
         * Using second argument in the String.split() method, we can control
         * the maximum number of substrings generated by splitting a string.
         */

        System.out.println("");
        temp = str.split(delimiter, 2);
        for (int i = 0; i < temp.length; i++)
            System.out.println(temp[i]);

    }

}

答案 3 :(得分:0)

你可以试试这个正则表达式:

    String test = "Test1 Avg. running Time: 66,3 [ms], (Ref: 424.0) ===> Well done, It is 80% faster"; 
    Pattern p = Pattern.compile("(\\d+[.,]?\\d+)");
    Matcher m = p.matcher(test);
    m.find();
    String avgRunningTime = m.group(1);
    m.find();
    String ref = m.group(1);
    System.out.println("avgRunningTime: "+avgRunningTime+", ref: "+ref);

这将打印:

    avgRunningTime: 66,3, ref: 424.0

您自然希望添加一些错误检查(例如,检查m.find()是否返回true)。