验证Android中的单元格号

tec*_*ner 3 string validation android

我有一个用户输入单元格编号的UI,数字存储在字符串变量中,然后存储到数据库中.

我想验证字符串以检查字符串是否不包含任何字符.

我怎么做?

下面是字符串代码.

EditText editText3 = (EditText) this.findViewById(R.id.editText2);
setNum = editText3.getText().toString(); //setNum would contain something link 8081124589
Run Code Online (Sandbox Code Playgroud)

Ale*_*dam 27

要验证字符串,请使用

if (setNum.matches(regexStr))
Run Code Online (Sandbox Code Playgroud)

其中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}$"
Run Code Online (Sandbox Code Playgroud)

有一个很长的正则表达式来验证美国的手机(7到10位数,允许扩展等).源自此答案:用于电话号码验证的全面正则表达式

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+))?$"
Run Code Online (Sandbox Code Playgroud)


Vai*_*ani 10

API级别8或以上:

public static final boolean isValidPhoneNumber(CharSequence target) {
    if (target == null || TextUtils.isEmpty(target)) {
        return false;
    } else {
        return android.util.Patterns.PHONE.matcher(target).matches();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的解决方案(或使用PhoneNumberUtils.isGlobalPhoneNumber).一个小调整,检查target == null是否必要,因为TextUtils.isEmpty会为您处理该检查. (3认同)