How To Use Regular Expressions In Java NetBeans
In this Java Tutorial we will see How To Use Regex (Regular Expressions) To Validate An Email Address And A Phone Number On Button "Check" Click Event Using Java NetBeans .
Project Source Code:
private void jButtonCheckActionPerformed(java.awt.event.ActionEvent evt) {
//Email Like: mail@mail.com => ^([\w]+)@([\w]+)\.([\w]+)$
//URL Like: http://www.google.com => ^(http://www\.)([\w]+)\.([\w]+)$
// email
Pattern pMail = Pattern.compile("^([\\w]+)@([\\w]+)\\.([\\w]+)$");
Matcher mMail = pMail.matcher(jTextFieldEmail.getText());
boolean isEmailValid = mMail.matches();
//jLabelEmail.setText(Boolean.toString(isEmailValid));
if(isEmailValid){
jLabelEmail.setText("Valid Email");
jLabelEmail.setForeground(Color.BLUE);
}else{
jLabelEmail.setText("InValid Email");
jLabelEmail.setForeground(Color.red);
}
// URL
Pattern pURL = Pattern.compile("^(http://www\\.)([\\w]+)\\.([\\w]+)$");
Matcher mURL = pURL.matcher(jTextFieldURL.getText());
boolean isURLValid = mURL.matches();
//jLabelURL.setText(Boolean.toString(isURLValid));
if(isURLValid){
jLabelURL.setText("Valid URL");
jLabelURL.setForeground(Color.green);
}else{
jLabelURL.setText("InValid URL");
jLabelURL.setForeground(Color.red);
}
}
OutPut:
Download Projects Source Code