假设我的日期范围的格式为1390573112to1490573112
,其中的数字是时间单位时间。有没有办法使用正则表达式来验证第二个数字是否大于第一个?
答案 0 :(得分:0)
编辑:我刚注意到您从未指定您选择的语言是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');
实现相同的结果