Regular expressions are used for defining String patterns that can be used for searching, manipulating and editing a text. These expressions are also known as Regex (short form of Regular expressions).
Note- import java.util.*;
:: Roll Number.
String get_data = user_data.getText();
Pattern pt_roll = Pattern.compile("[A-Za-z]{1}[0-9]{3,}");
Matcher mt_roll = pt_roll.matcher(get_data);
if (mt_roll.matches()) {
JOptionPane.showMessageDialog(this, "Valid Roll");
} else {
JOptionPane.showMessageDialog(this, "Invalid Roll");
}
//Output- N100
::Username
String get_data = user_data.getText();
Pattern pt_user = Pattern.compile("[a-zA-Z0-9]{2,}");
Matcher mt_user = pt_user.matcher(get_data);
if (mt_user.matches()) {
JOptionPane.showMessageDialog(this, "Valid User");
} else {
JOptionPane.showMessageDialog(this, "Invalid username");
}
//Output- ram123
::Full Name
String get_data = user_data.getText();
Pattern pt_name = Pattern.compile("[a-zA-Z ]{2,}");
Matcher mt_name = pt_name.matcher(get_data);
if (mt_name.matches()) {
JOptionPane.showMessageDialog(this, "Valid Name");
} else {
JOptionPane.showMessageDialog(this, "Invalid Name");
}
//Output- Ram Pukar
:: Phone Number
Pattern pt_phone = Pattern.compile("\\d{4}-\\d{6}");
Matcher mt_phone = pt_phone.matcher(get_data);
if (mt_phone.matches()) {
JOptionPane.showMessageDialog(this, "Valid Phone");
} else {
JOptionPane.showMessageDialog(this, "In-Valid Phone Number must be in the form XXXX-XXXXXX");
}
//Output- 1234-1234567890
::E-Mail Address
String get_data = user_data.getText();
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pt_mail = Pattern.compile(EMAIL_PATTERN);
Matcher mt_mail = pt_mail.matcher(get_data);
if (mt_mail.matches()) {
JOptionPane.showMessageDialog(this, "Valid Email");
} else {
JOptionPane.showMessageDialog(this, "Invalid Email");
}
//Output- example@gmail.com
:: Salary, Numerical
String get_data = user_data.getText();
Pattern pt_salary = Pattern.compile("\\d{1,}");
Matcher mt_salary = pt_salary.matcher(get_data);
if (mt_salary.matches()) {
JOptionPane.showMessageDialog(this, "Valid Salary");
} else {
JOptionPane.showMessageDialog(this, "Invalid Salary");
}
//Output- 1000.123
0 comments:
Post a Comment