如何使用 2 个以上的分隔符

How to use more than 2 delimiters

我想划,\s,但我也想划\n,目前我想到的是,\s||\n,但这行不通,有人知道吗?它当然可以用作分隔符,但它返回 IPHONE , 7.0, 4, ., 7, A, false, 0 而我想要返回 IPHONE 7, 4.7, A10, GSM, JET BLACK, 32GB, TRUE, 700

我正在扫描的文件是这样的:

IPHONE 7, 4.7, A10, GSM, JET BLACK, 32GB, TRUE, 700
IPAD AIR 2, 9.7, A8, TRUE, SILVER, 64GB, 400

我用来扫描它的代码是这样的:

public static iPhone read(Scanner sc) {
        boolean touchtech = false;
        //int price = 12;
        sc.next();
        sc.useDelimiter(",\s||\n");
        String model = sc.next();
        double screensize = sc.nextDouble();
        String processor = sc.next();
        String modem = sc.next();
        String color = sc.next();
        String memory = sc.next();
        String touchtechtest = sc.next();
        if(touchtechtest.equals("TRUE")) {
            touchtech = true;
        }
        int price = sc.nextInt();
        sc.close();
        iPhone res = new iPhone(model, screensize, processor, modem, color, memory, touchtech, price);
        return res;
    }

useDelimiter 收到一个正则表达式。因此,在您的情况下,正确的字符串应该是 "(,\s|\n)"。您的 OR 条件放在圆括号中,并由单竖线分隔,而不是双竖线。

你也可以参考这个优秀的回答:

有时 String.class 本身就足以满足您的需求。为什么不使用正则表达式拆分行并对结果进行操作?例如

public static iPhone read(Scanner sc) { // Better yet just make it received a String
    final String line = sc.nextLine();
    final String [] result = line.split("(,)\s*");

    // count if the number of inputs are correct
    if (result.length == 8) {
        boolean touchtech = false;
        final String model = result[0];
        final double screensize = Double.parseDouble(result[1]);
        final String processor = result[2];
        final String modem = result[3];
        final String color = result[4];
        final String memory = result[5];
        final String touchtechtest = result[6];
        if(touchtechtest.equals("TRUE")) {
            touchtech = true;
        }
        final int price = Integer.parseInt(result[7]);
        return new iPhone(model, screensize, processor, modem, color, memory, touchtech, price);
    }
    return new iPhone();// empty iphone
}