验证 IP 永远不会成功
Validating IP never succeeds
用户在 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 地址,代码永远不会将其视为有效并且日志显示 "doesn't match!"。我做错了什么?
将 onPreferenceChange()
方法中的测试更改为:
IP_ADDRESS.matcher(newValue.toString()).matches()
用户在 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 地址,代码永远不会将其视为有效并且日志显示 "doesn't match!"。我做错了什么?
将 onPreferenceChange()
方法中的测试更改为:
IP_ADDRESS.matcher(newValue.toString()).matches()