Say I have a have a date range in a format like 1390573112to1490573112
, where the numbers are epoch unix time. Is there a way to use regex to validate that the second number is greater than the first?
Edit: I just noticed that you never specified your language of choice to be JavaScript. Do you have a particular language that you are using? As dawg mentioned it's not reflex that will solve this alone.
Not regex alone, but you could use it to get the numbers and then something like this to compare them:
// 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
Of course you don't even need regex if your use case is that simple. You could replace this line:
var timestamps = str.match(/(\d+)to(\d+)/).slice(1);
With this:
var timestamps = str.split('to');
to achieve the same result