Nul*_*ion 10
如何在java中验证字符串?
一种常见的方法是使用正则表达式或正则表达式.在Java中,您可以使用该String.matches(String regex)方法.使用正则表达式,我们说您匹配模式的字符串如果匹配成功,则.matches()返回true.
只允许字符而不是数字?
// You can use this pattern:
String regex = "^[a-zA-Z]+$";
if (str.matches(regex)) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
邮件验证?
电子邮件地址有一个非常复杂的规范,这需要一个怪异的正则表达式准确.这个很好,很短,但不完全正确:
String regex = "\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b";
if (str.matches(regex)) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
如果你真的想调查它:如何验证电子邮件和比较电子邮件验证正则表达式(PHP).
这是开始使用正则表达式的绝佳资源:http:
//www.regular-expressions.info
对于只有字符的字符串尝试
private boolean verifyLastName(String lname)
{
lname = lname.trim();
if(lname == null || lname.equals(""))
return false;
if(!lname.matches("[a-zA-Z]*"))
return false;
return true;
}
Run Code Online (Sandbox Code Playgroud)
用于电子邮件验证尝试
private boolean verifyEmail(String email)
{
email = email.trim();
if(email == null || email.equals(""))
return false;
if(!email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$"))
return false;
return true;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42800 次 |
| 最近记录: |