2012-10-31 77 views
0

我正在製作java IRC庫,我需要一種方法來查看某個用戶是否與可包含通配符字符的主機掩碼相匹配。不使用正則表達式的最簡單方法是什麼?Java簡單通配符匹配

一些例子:

// Anything works 
    * 
      server.freenode.net ✔ 

    // Any nickname/user/host works 
    *!*@*: 
      [email protected] ✔ 

    // Any nickname works (may have multiple nicknames on the same user) 
    *[email protected]/nebkat: 
      [email protected]/nebkat ✔ 
      [email protected]/nebkat ✔ 
      [email protected]/hacker ✘ 

    // Anything from an ip 
    *!*@123.4.567.89: 
      [email protected][email protected][email protected] ✘ 

    // Anything where the username ends with nebkat 
    *!*[email protected]* 
      [email protected]/nebkat ✔ 
      [email protected]/nebkat ✔ 
      [email protected]/nebkat ✘ 
+3

爲什麼不使用正則表達式?這看起來像一個正則表達式的完美匹配。 –

+0

@TomJohnson我認爲特殊字符可能會干擾,我將不得不處理該問題。既然它只有一個通配符,我認爲沒有正則表達式會更簡單? – nebkat

+0

你總是可以逃避特殊字符...... – jlordo

回答

2

結束了與此:

public static boolean match(String host, String mask) { 
    String[] sections = mask.split("\\*"); 
    String text = host; 
    for (String section : sections) { 
     int index = text.indexOf(section); 
     if (index == -1) { 
      return false; 
     } 
     text = text.substring(index + section.length()); 
    } 
    return true; 
} 
+0

請注意,當'host'爲'abcdef'且'mask'爲'abc'時,該函數的答案仍然爲「true」。 – Yonatan