Regex 日期范围的正则表达式匹配
假设我有一个日期范围,格式类似于Regex 日期范围的正则表达式匹配,regex,validation,datetime,epoch,Regex,Validation,Datetime,Epoch,假设我有一个日期范围,格式类似于1390573112to14905733112,其中数字是时间。有没有一种方法可以使用正则表达式来验证第二个数字是否大于第一个数字?编辑:我刚刚注意到,您从未将所选语言指定为JavaScript。您是否使用了特定的语言?正如道格提到的,光靠反射并不能解决这个问题 不仅仅是正则表达式,但您可以使用它来获取数字,然后类似这样的东西来比较它们: // Method to compare integers. var compareIntegers = function(
1390573112to14905733112
,其中数字是时间。有没有一种方法可以使用正则表达式来验证第二个数字是否大于第一个数字?编辑:我刚刚注意到,您从未将所选语言指定为JavaScript。您是否使用了特定的语言?正如道格提到的,光靠反射并不能解决这个问题
不仅仅是正则表达式,但您可以使用它来获取数字,然后类似这样的东西来比较它们:
// 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.split('to');
要获得相同的结果您需要使用一种具有词汇排序或从字符串到int的转换的语言。不仅仅是正则表达式。谢谢,这回答了我的问题,我想知道单独使用正则表达式是否可行,如果不可行,应该采取什么方法。
var timestamps = str.split('to');