日期范围的正则表达式匹配

Regex matching for date range

假设我有一个格式如 1390573112to1490573112 的日期范围,其中数字是 epoch unix 时间。有没有办法使用正则表达式来验证第二个数字是否大于第一个?

编辑:我刚刚注意到您从未将您选择的语言指定为 JavaScript。您有正在使用的特定语言吗?正如 dawg 所提到的,单靠反射并不能解决这个问题。


不仅仅是正则表达式,但您可以使用它来获取数字,然后用类似这样的方法来比较它们:

// Method to compare integers.
var compareIntegers = function(a, b) {
  /* Returns:
   1 when b > a
   0 when b === a
  -1 when b < a
  */
  return (a === b) ? 0 : (b > a) ? 1 : -1;
};

// Method to compare timestamps from string in format "{timestamp1}to{timestamp2}"
var compareTimestampRange = function(str) {
  // Get timestamp values from string using regex
  // Drop the first value because it contains the whole matched string
  var timestamps = str.match(/(\d+)to(\d+)/).slice(1);
  /* Returns:
   1 when timestamp2 > timestamp1
   0 when timestamp2 === timestamp1
  -1 when timestamp2 < timestamp1
  */
  return compareIntegers.apply(null, timestamps);
}

// Test!
console.log(compareTimestampRange('123to456')); // 1
console.log(compareTimestampRange('543to210')); // -1
console.log(compareTimestampRange('123to123')); // 0
console.log(compareTimestampRange('1390573112to1490573112')); // 1

当然,如果您的用例如此简单,您甚至不需要正则表达式。您可以替换此行:

var timestamps = str.match(/(\d+)to(\d+)/).slice(1);

有了这个:

var timestamps = str.split('to');

达到相同的结果