正则表达式,用于验证包含整数范围的csv行的升序

时间:2016-08-24 14:23:29

标签: regex

我们说我们有范围

  • < 0100>
  • (100,1000>
  • (1000,10000>
  • (10000,无穷大)

表示为csv行如下:

0100; 100,1000; 1000,10000; 10000

什么是正则表达式,它将验证csv行是否按升序包含整数范围?

1 个答案:

答案 0 :(得分:1)

你真的不会用正则表达式走得太远。此外,通过算法验证您的需求非常简单。

例如,在Java中:

public static boolean ascendingOrder(String csv) {
    String[] values = csv.split(",|\\;"); // Split on either "," or ";"
    for (int i = 1; i < values.length; i++) {
        int lastValue = Integer.parseInt(values[i-1]);
        int currentValue = Integer.parseInt(values[i]);
        if (i%2==0) { // If it's the lower bound, should be greater or equal than last higher bound
            if (lastValue > currentValue) return false;
        } else { // If it's the higher bound, ensure no empty interval
            if (lastValue >= currentValue) return false;
        }
    }
    return true;
}

这可以验证范围是按顺序递增而且不会重叠。