2017-03-27 120 views
-1

假設我有一個像1390573112to1490573112這樣的格式的日期範圍,其中數字是紀元unix時間。有沒有辦法使用正則表達式來驗證第二個數字大於第一個?日期範圍的正則表達式匹配

+1

您需要使用的語言,要麼具有從字符串爲int的詞彙排序或轉換。不是單獨的正則表達式。 – dawg

回答

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'); 

,以達到相同的結果

+0

謝謝,這回答了我的問題,我想知道是否可以使用正則表達式,如果不是,應該採取什麼方法。 –