Java Reference
In-Depth Information
Using regexes in Java: Test for a Pattern
Problem
You're ready to get started using regular expression processing to beef up your Java code by
testing to see if a given pattern can match in a given string.
Solution
Use the Java Regular Expressions Package, java.util.regex .
Discussion
The good news is that the Java API for regexes is actually easy to use. If all you need is to
find out whether a given regex matches a string, you can use the convenient boolean
matches() method of the String class, which accepts a regex pattern in String form as its
argument:
iif ( inputString . matches ( stringRegexPattern )) {
// it matched... do something with it...
}
This is, however, a convenience routine, and convenience always comes at a price. If the
regex is going to be used more than once or twice in a program, it is more efficient to con-
struct and use a Pattern and its Matcher (s). A complete program constructing a Pattern
and using it to match is shown here:
public
public class
class RESimple
RESimple {
public
public static
void main ( String [] argv ) {
String pattern = "^Q[^u]\\d+\\." ;
String [] input = {
"QA777. is the next flight. It is on time." ,
"Quack, Quack, Quack!"
static void
};
Pattern p = Pattern . compile ( pattern );
for
for ( String in : input ) {
boolean
boolean found = p . matcher ( in ). lookingAt ();
Search WWH ::




Custom Search