2010-09-13 110 views
18

HI all, 我在android(作爲客戶端)和PC(作爲服務器)之間使用簡單的套接字通信。我正在使用EditText作爲IP地址。我想驗證在EditText字段中輸入的IP地址。可以請一些人幫助我..我需要它。提前致謝。在android中驗證IP

回答

32

如果您的目標是API級別8,則可以使用Patterns.IP_ADDRESS全局正則表達式。您可以直接包括這個表達式在您的項目,如果你的目標與Android < 2.2設備:

private static final Pattern IP_ADDRESS 
    = Pattern.compile(
     "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]" 
     + "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]" 
     + "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}" 
     + "|[1-9][0-9]|[0-9]))"); 
Matcher matcher = IP_ADDRESS.matcher("127.0.0.1"); 
if (matcher.matches()) { 
    // ip is correct 
} 
15

要檢查IP作爲它正在進入你可能想使用它代替:

private static final Pattern PARTIAl_IP_ADDRESS = 
      Pattern.compile("^((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])\\.){0,3}"+ 
          "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])){0,1}$"); 

ipEditText.addTextChangedListener(new TextWatcher() {      
    @Override public void onTextChanged(CharSequence s, int start, int before, int count) {}    
    @Override public void beforeTextChanged(CharSequence s,int start,int count,int after) {}    

    private String mPreviousText = "";   
    @Override 
    public void afterTextChanged(Editable s) {   
     if(PARTIAl_IP_ADDRESS.matcher(s).matches()) { 
      mPreviousText = s.toString(); 
     } else { 
      s.replace(0, s.length(), mPreviousText); 
     } 
    } 
}); 
+0

謝謝你,非常有用:) – Bartando 2016-03-25 17:50:07

+0

不錯的一個!謝謝 – artman 2016-07-29 11:54:55

+0

這是真棒,很容易推廣到某種「RegexValidator」,可以很容易地添加到任何EditText爲其他用例:) – user1405990 2016-10-19 02:20:48

19
Patterns.IP_ADDRESS.matcher(url).matches(); 
+0

儘可能簡單。 – Ahsan 2017-10-26 12:29:12