2016-03-02 86 views
0

我正在做一個函數,它需要一個例子和一個ip地址。例如。數組比較?

compare('192.168.*','192.168.0.42'); 

asterix表示ip的以下部分可以是任何東西。該函數根據example和ip是否匹配返回true或false。我試過這種解決方案。

var compare = function(example, ip){ 
    var ex = example.split("."); 
    var ip = ip.split("."); 
    var t = 0; 
    for(var i=0; i<4; i++){ 
    if(ex[i] == ip[i] || ex[i] == "*" || typeof ex[i] === 'undefined' && ex[i-1] == "*"){ 
      t++ 
      if(t==4){ 
      return true 
      } 
     }else{ 
     return false; 
     } 
    } 
} 

在此解決方案中使用正則表達式的主要優點是什麼?什麼是最好的正則表達式來做到這一點?

+0

正則表達式是用於字符串比較,所以你可以遍歷數組,並使用正則表達式來測試每個值。 –

+0

您對JavaScript或Java的問題? –

回答

1

如何檢查它們是否不相等然後返回false?

var compare = function(example, ip){ 
 

 
    // You should have some basic IP validations here for both example and ip. 
 
    
 
    var ex = example.split("."); 
 
    var ip = ip.split("."); 
 
    for(var i=0; i<ex.length; i++){ 
 
    
 
     if(ex[i]=='*') 
 
     break; 
 
    
 
     if(ex[i]!=ip[i]) 
 
     return false; 
 
    
 
    } 
 
    
 
    return true; 
 
} 
 

 
alert(compare('333.321.*','333.321.345.765')); 
 
alert(compare('333.322.*','333.321.345.765')); 
 
alert(compare('333.321.345.*','333.321.345.765'));

+0

有效,直到你想要「333.444。*。555」這樣的東西。 – zzzzBov

0

這種方式去更好地使用正則表達式。試試這個:

function compare(example, ip) { 
    var regexp = new RegExp('^' + example.replace(/\./g, '\\.').replace(/\*/g, '.*')); 
    return regexp.test(ip); 
} 

compare('192.168.*', '192.168.0.42'); // => true 
compare('192.167.*', '192.168.0.42'); // => false 

這是做什麼的,它將您的模式轉換爲正則表達式。正則表達式在匹配字符串時非常強大。它也包括這樣的情況:

compare('192.168.*.42', '192.168.1.42'); // => true 
compare('192.167.*.42', '192.168.1.43'); // => false