我正在尝试设置电子邮件地址输入的常规验证验证。
我有这个java类进行验证:
public class EmailValidator implements Validator {
@Override
public void validate(FacesContext facesContext,
UIComponent uIComponent, Object value) throws ValidatorException {
//Get the component's contents and cast it to a String
String enteredEmail = (String)value;
//Set the email pattern string
Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
//Match the given string with the pattern
Matcher m = p.matcher(enteredEmail);
//Check whether match is found
boolean matchFound = m.matches();
if (!matchFound) {
FacesMessage message = new FacesMessage();
message.setDetail("Email not valid - The email must be in the format yourname@yourdomain.com");
message.setSummary("Email not valid - The email must be in the format yourname@yourdomain.com");
message.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message);
}
}
}
此代码中有一个默认模式。但是,我试图用另一种模式替换它。
模式:
/ ^(:(:(:???[^ @ “?[] \ x5c \ x00- \ X20 \ x7f- \ XFF] | \ x5c(= [@,”[] \ x5c \ x00- \ X20 \ x7f- \ XFF]))(?:[^ @ “?[] \ x5c \ x00- \ X20 \ x7f- \ XFF] |(小于= \ x5c)[@”,[ ] \ x5c \ x00- \ X20 \ x7f- \ XFF] | \ x5c(?= [@,“[] \ x5c \ x00- \ X20 \ x7f- \ XFF])|。(?= [^]) ){1,62}(?:[^ @ “?[] \ x5c \ x00- \ X20 \ x7f- \ XFF] |(小于= \ x5c)[@,”[] \ x5c \ x00- \ X20 \ x7f- \ XFF])| [^ @, “[] \ x5c \ x00- \ X20 \ x7f- \ XFF] {1,2})|。”(:?[^“] |(小于= \ x5c) “){1,62}”)@(:({64})(:[A-ZA-Z0-9] [A-ZA-Z0-9 - ] {1?!? ,61} [A-ZA-Z0-9] | [A-ZA-Z0-9])+(?: XN - [A-ZA-Z0-9] + |。?。?[A-ZA -Z] {2,6-})| [(:[0-1?] \ d \ d | 2 [0-4] \ d | 25 [0-5])(:????(: 0-1] \ d \ d |?2 [0-4] \ d | 25 [0-5])){3}])$ /
我可以知道可以使用这种模式吗?或者我需要放一些括号等使其工作?我现在收到非法的表达错误开始。
答案 0 :(得分:5)
答案 1 :(得分:0)
我确信可以使用正则表达式 ,但您必须将其正确插入到代码中。但是,检查电子邮件是否有效的最佳方法是向其发送电子邮件。 Here是使用正则表达式进行电子邮件验证的好网站,当然您也可以在此网站上搜索许多类似的问题。
答案 2 :(得分:0)
如果您正在尝试进行电子邮件验证,此模式可以正常工作,并且更短^[a-z0-9!#$%&'*+/=?^_
{|}〜 - ] +(?:\。[a-z0-9!#$%&'* * + / =?^ _ {|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$
我使用java的regex util包(java.util.regex.*
)这里是关于它的文档和一般java中的正则表达式:
http://java.sun.com/developer/technicalArticles/releases/1.4regex/
答案 3 :(得分:0)
您可以使用该RegEx(或任何您想要的),但请记住在java字符串中跳过反斜杠\
(通过输入两个\\
)。
Here是一个允许你将正则表达式字符串转换为Java字符串的页面,即它可以为你完成所有奇怪字符的转义....(页面似乎现在已经关闭了,但它昨天正在运行,所以稍后再办理入住......)
答案 4 :(得分:0)
请试试这个,对我很好。
String expressionForEmail = "^[\\w\\.-]+@([\\w\\-]+\\.)+[a-zA-Z]{2,4}$";
答案 5 :(得分:-2)
您可以将此表达式用于电子邮件验证“[A-Za-z] + @ + [A-Za-z] + \。+ [A-Za-z] {2,4} + $” 这样做要简单得多。