安卓手机号正则验证时Log打印结果为true,赋值布尔变量后变为false
根本原因
Java/Android 正则的Matcher类的find()方法具备状态记忆特性:每次调用find()都会从上次匹配结束的位置向后检索新的匹配项,你的输入手机号9048857563只有一段符合规则的内容,所以:
- 第一次在Log打印时调用
match.find()成功匹配,返回true,指针移动到字符串末尾 - 第二次赋值给
isPhoneValid时再次调用find(),此时指针已经在末尾,没有新的匹配项,返回false - 后续if判断、else分支里的
find()调用全部返回false,所以出现了只有第一次打印为true的现象
修复方案
只调用一次find(),将结果提前缓存到变量中,所有后续逻辑都使用缓存的结果,不要重复调用find()。如果需要要求正则匹配整个字符串,也可以直接用matches()方法替换find()+group()等于原字符串的判断逻辑,更简洁。
修正后代码示例
Log.d("testi3", "id " + edit_number.getText()); if (number.isEmpty()) { Log.d("testi3", "id empty" + edit_number.getText()); edit_number.setError(getResources().getString(R.string.phone_error)); isPhoneValid = false; } else { Log.d("testi3", "id else " + edit_number.getText()); // 正则添加^$限定全文匹配,不需要额外判断group等于原字符串 Pattern ptrn = Pattern.compile("^[7-9][0-9]{9}$"); Matcher match = ptrn.matcher(number); // 只调用一次匹配,缓存结果 boolean isMatch = match.matches(); Log.d("testi3", "id else 1 " + isMatch); isPhoneValid = isMatch; Log.d("testi3", "id else validi" + isPhoneValid); if (isMatch) { Log.d("testi3", "id else 2 " + isMatch); isPhoneValid = true; } else { Log.d("testi3", "id else 3 " + isMatch); edit_number.setError(getResources().getString(R.string.phone_error)); isPhoneValid = false; } }
内容的提问来源于stack exchange,提问作者Sayooj
相关产品推荐
相关产品推荐

