正则表达式来验证CSV行包含整数范围按升序排列

问题描述:

比方说,我们有范围正则表达式来验证CSV行包含整数范围按升序排列

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

表示为CSV行如下:

0100; 100,1000; 1000,10000; 10000

什么是正则表达式,将验证CSV行包含以升序的整数的范围?

+1

为什么要使用纯正则表达式,而不是数学运算符? – hjpotter92

+1

正则表达式并不意味着比较数字。我想你会想寻找任何其他的解决方案,而不是依赖于这个正则表达式。 –

+0

我认为正则表达式在这里是一个糟糕的选择。在Java中,我只是用分号分隔每行,然后按顺序遍历结果数组,检查以确保每个数字不断增加。 –

你真的不会走远一个正则表达式。另外,使用一种算法来验证你想要的是很简单的。

例如,在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; 
} 

这将验证的范围是按升序排列,不重叠。