予有其中用户进入细胞数量的UI和号码存储在一个字符串变量然后将其存储到数据库中。
我想验证字符串检查字符串是否不包含任何字符。
我该怎么办呢?
下面是字符串code。
的EditText editText3 =(EditText上)this.findViewById(R.id.editText2);
。setNum = editText3.getText()的toString(); // setNum将包含一些链接8081124589
解决方案
要验证一个字符串,用
如果(setNum.matches(regexStr))
在这里regexStr可以是:
仅 //比赛号码
字符串regexStr =^ [0-9] * $
//只匹配10位数字
字符串regexStr =^ [0-9] {10} $
//匹配数字和破折号,任何顺序真的。
字符串regexStr =^ [0-9 \\ - ] * $
//匹配9999999999,1-999-999-9999和999-999-9999
字符串regexStr =^(1 \\ - )?[0-9] {3} \\ - ?[0-9] {3} \\ - ?[0-9] {4} $
有一个很长的正则表达式来验证电话在美国(7至10位,扩展允许的,等等)。来源是这样的回答:A COM prehensive的正则表达式的电话号码验证
字符串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+))?$"
I have a UI where user enters the cell number and the number is stored in a string variable and then its stored into the database.
I want to validate the string to check whether the string does not contain any characters.
How do I do that?
Below is the string code.
EditText editText3 = (EditText) this.findViewById(R.id.editText2);
setNum = editText3.getText().toString(); //setNum would contain something link 8081124589
解决方案
To validate a string, use
if (setNum.matches(regexStr))
where regexStr can be:
//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}$"
There's a very long regex to validate phones in the US (7 to 10 digits, extensions allowed, etc.). The source is from this answer: 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+))?$"