Java Reference
In-Depth Information
To validate these kinds of strings, you need to recognize the pattern you are looking for. For
example, in the simplest form of e-mail address validation, the string should consist of some
text (at least one character) plus an @ sign followed by some text for domain name. Let's ignore
any other details for now.
You need a way to express the recognized pattern. A regular expression is used to describe
such a pattern.
You need a program that can match the pattern against the input string. Such a program is also
known as a regular expression engine.
Suppose you want to test whether a string is of the form X@X , where X is any character. Strings "a@a" , "b@f" , "3@h"
are in this form. You can observe a pattern here. The pattern is “A character followed by @ , which is followed by a
character.” How do you express this pattern in Java?
The string ".@." will represent your regular expression in this case. In ".@." , the dots have a special meaning.
They represent any character. All characters that have special meanings inside a regular expression are called
metacharacters. I will discuss metacharacters in the next section. The String class contains a matches() method.
It takes a regular expression as an argument and returns true if the whole string matches the regular expression.
Otherwise, it returns false . The signature of this method is
boolean matches(String regex)
The program listed in Listing 14-1 illustrates the use of the matches() method of the String class.
Listing 14-1. Matching a String Against a Pattern
// RegexMatch.java
package com.jdojo.regex;
public class RegexMatch {
public static void main(String[] args) {
// Prepare a regular expression to represent a pattern
String regex = ".@.";
// Try matching many strings against the regular expression
RegexMatch.matchIt("a@k", regex);
RegexMatch.matchIt("webmaster@jdojo.com", regex);
RegexMatch.matchIt("r@j", regex);
RegexMatch.matchIt("a%N", regex);
RegexMatch.matchIt(".@.", regex);
}
public static void matchIt(String str, String regex) {
// Test for pattern match
if (str.matches(regex)) {
System.out.println(str + " matches the regex " + regex);
}
else {
System.out.println(str + " does not match the regex " + regex);
}
}
}
 
Search WWH ::




Custom Search