Java provides support for regular expressions and for matching the patterns (i.e. specific text in the string) by providing the following elements:
- The java.util.regex.Pattern class
- The regular expression constructs
- The java.util.regex.Matcher class
The simplest form of a regular expression is a literal string search. For example, if you want to find out a specific word such as 'java' in the input text. You will build an expression construct for that. However, you can build very sophisticated expressions using java regular expression constructs. Consider the following expression:
[A-Za-Z0-9]
This expression mean any character in the range of A through Z, a through z, or 0 through 9 (any letter or digit) will match this pattern. For all rest of the characters the following regular expression construct will match.
[^A-Za-z0-9]
Where the character ^ is used for negate.
Now I a assume that you are familiar with basics of java regular expressions, So let explore it with a simple example of email validation using java regex.
EmailValidator.java
import java.util.regex.*;
public class EmailValidator {
public static void main(String[] args)
{
String
email = "";
if (args.length < 1) {
System.out.println("Command
syntax: " +
"java
EmailValidator <emailAddress>");
System.exit(0);
}
else {
email
= args[0];
}
// Look for for
email addresses starting with
// invalid symbols:
dots or @ signs.
Pattern
p = Pattern.compile("^\\.+|^\\@+");
Matcher
m = p.matcher(email);
if (m.find()) {
System.err.println("Invalid email
address: " +
"starts with a
dot or an @ sign.");
System.exit(0);
}
// Look for email
addresses that start with www.
p
= Pattern.compile("^www\\.");
m
= p.matcher(email);
if (m.find()) {
System.out.println("Invalid email
address: " +
"starts with
www.");
System.exit(0);
}
p
= Pattern.compile("[^A-Za-z0-9\\@\\.\\_]");
m
= p.matcher(email);
if (m.find()) {
System.out.println("Invalid email
address: " +
"contains
invalid characters");
}
else {
System.out.println(args[0] +
" is a valid email address.");
" is a valid email address.");
}
}
}
To execute the the above program, you need to give a string as a command-line argument, for example:
java EmailValidator www.naeemgik.com@aol.com
This will produce the following output:
Invalid email address: starts with www.
Similarly you can test the above code with different valid and invalid email addresses provided as command line.
Reference(s): SCJP Exam for J2SE 5
No comments:
Post a Comment