我有一个 UI,用户可以在其中输入单元格编号,该编号存储在字符串变量中,然后存储到数据库中。
我想验证字符串以检查字符串是否不包含任何字符。
我该怎么做?
下面是字符串代码
EditText editText3 = (EditText) this.findViewById(R.id.editText2);
setNum = editText3.getText().toString(); //setNum would contain something link 8081124589
最佳答案
要验证一个字符串,使用
if (setNum.matches(regexStr))
regexStr 可以是:
//matches numbers only
String regexStr = "^[0-9]*$"
//matches 10-digit numbers only
String regexStr = "^[0-9]{10}$"
//matches numbers and dashes, any order really.
String regexStr = "^[0-9\\-]*$"
//matches 9999999999, 1-999-999-9999 and 999-999-9999
String regexStr = "^(1\\-)?[0-9]{3}\\-?[0-9]{3}\\-?[0-9]{4}$"
在美国有一个非常长的正则表达式来验证电话(7 到 10 位数字,允许分机等)。来源来自这个答案:A comprehensive regex for phone number validation
String regexStr = "^(?:(?:\\+?1\\s*(?:[.-]\\s*)?)?(?:\\(\\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\\s*\\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\\s*(?:[.-]\\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\\s*(?:[.-]\\s*)?([0-9]{4})(?:\\s*(?:#|x\\.?|ext\\.?|extension)\\s*(\\d+))?$"
关于android - 在 Android 中验证手机号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5958665/