验证IP永远不会成功

时间:2015-06-20 10:06:19

标签: java android validation ip matcher

用户在EditTextPreference中输入IP地址,我尝试使用以下代码验证IP:

private EditTextPreference ipPref;
private Matcher matcher;
private SharedPreferences settings;
private 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]))");

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.settings);

    //PREF_IP is the android:key of the EditTextPreference
    ipPref = (EditTextPreference) getPreferenceManager().findPreference("PREF_IP"); 
    settings = PreferenceManager.getDefaultSharedPreferences(this);
    matcher = IP_ADDRESS.matcher(settings.getString("PREF_IP", "0.0.0.0"));

ipPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {            
        public boolean onPreferenceChange(Preference preference, Object newValue) {

            try 
            {
                if(matcher.matches()){
                    Log.d("settings", "matches!");
                    return true;
                }else{
                    Log.d("settings", "doesn't match!");
                    return false;
                }
            }
            catch(Exception e)
            {
                return false;
            }
        }
    }); 
}

如果我输入有效的IP地址,代码永远不会将其视为有效,并且日志显示“不匹配!”。我做错了什么?

1 个答案:

答案 0 :(得分:1)

onPreferenceChange()方法中的测试更改为:

 IP_ADDRESS.matcher(newValue.toString()).matches()