Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning Regular Expressions 2005.pdf
Скачиваний:
95
Добавлен:
17.08.2013
Размер:
25.42 Mб
Скачать

Chapter 25

Introduction to the java.util.regex Package

The java.util.regex package was introduced in Java 2 Standard Edition version 1.4. So the examples described in this chapter will not work in versions prior to Java 1.4.

The java.util.regex package has three classes: Pattern, Matcher, and PatternSyntaxException. Each of those classes is described later in this section. First, look at how to obtain and set up a version of Java that supports the java.util.regex package.

Obtaining and Installing Java

If you don’t have Java but want to work with the examples in this chapter, you will need to download and install a recent version of Java 2 Standard Edition, which supports java.util.regex. At the time of this writing, you have two choices: Java 1.4.2 and Java 5.0. Each of those versions belongs to the broad category of Java 2.

Java 2 Standard Edition can be downloaded from the Sun Java site at http://java.sun.com. At the time of this writing, information about the currently available versions of Java 2 Standard Edition can be found at http://java.sun.com/j2se/.

Installation instructions are provided online on Sun’s Java site for 32-bit and 64-bit platforms. At the time of this writing, installation information can be accessed from http://java.sun.com/j2se/ 1.5.0/install.html.

The naming of Java 5.0 or 1.5 is inconsistent in Sun’s documentation. For example, the preceding URL uses the term 1.5.0 to refer to what the Web page calls Java 5.0. The two terms Java 1.5 and Java 5.0 refer to the same version of Java.

Installing Java on the Windows platform is straightforward. An executable installer requires only a few simple choices to be made. At the time of this writing, the installer can be downloaded from http://java.sun.com/j2se/1.5.0/download.jsp. There is also an extensive bundle of Java 5.0 documentation available for download from the same URL.

The Pattern Class

The java.util.regex.Pattern class is a compiled representation of a regular expression. The Pattern class has no public constructor. To create a pattern object, you must use the class’s static compile() method.

A regular expression pattern is expressed as a string. The regular expression is compiled into an instance of the Pattern class using the compile() method. The Pattern object can then be used to create a Matcher object, which can match any arbitrary character sequence against the regular expression pattern associated with the Pattern object.

Use of the Pattern and Matcher objects typically follows this sort of pattern:

Pattern myPattern = Pattern.compile(“someRegularExpression”); Matcher myMatcher = myPattern.matcher(“someString”);

boolean myBoolean = myMatcher.matches();

620

Regular Expressions in Java

The preceding code assumes the existence in the code of the following import statement:

import java.util.regex;

Instances of the Pattern class are immutable and are, therefore, safe for use by multiple threads.

Using the matches() Method Statically

If you want to use a regular expression pattern only once, the option exists to use the matches() method statically. Using the matches() method statically is a convenience when matching is to be carried out once only.

The matches() method takes two arguments. The first argument is a regular expression pattern, expressed as a String. The second argument is a character sequence, a CharSequence, which is the string against which matching is to be attempted.

To use the matches() method statically, you would write code such as the following:

Pattern.matches(somePattern, someCharacterSequence);

So if you wanted to match the pattern [A-Z] against the string George W. Bush and John Kerry were the US Presidential candidates in 2004 for the two main political parties, you could do so as follows:

boolean myBoolean = Pattern.matches(“[A-Z]”, “George W. Bush and John Kerry were

the US Presidential candidates in 2004 for the two main political parties”);

Because the character sequence, the second argument to the matches() method, contains at least one uppercase alphabetic character, the myBoolean variable would contain the value true.

Two Simple Java Examples

The aim of the first example is to find any occurrence of the character sequence the and the following characters of the word containing it. The test string is as follows:

The theatre is the greatest form of live entertainment according to thespians.

The problem statement can be written as follows:

Match words that contain the character sequence t followed by h, followed by e, and the rest of the word, until a word boundary is found.

A pattern to allow you to solve the problem statement is:

the[a-z]*\b

First, you simply match the literal character sequence the. Then you match zero or more lowercase alphabetic characters, indicated by the pattern [a-z]. Finally, a word boundary, indicated by \b, is matched.

621

Chapter 25

When you write the pattern the[a-z]*\b in an assignment statement, it is necessary to escape the \b metacharacter. So you write the pattern as the[a-z]*\\b. If you retrieve the value for a pattern from a text file, it isn’t necessary to escape metacharacters in this way.

The following instructions assume that you have installed Java so that it can be accessed from any directory on your computer.

Try It Out

Using the Pattern and Matcher Classes

1.In a text editor, type the following Java code:

import java.util.regex.*;

public class Find_the{

public static void main(String args[]) throws Exception{

String myTestString = “The theatre is the greatest form of live entertainment according to thespians.”;

String myRegex = “the[a-z]*\\b”;

Pattern myPattern = Pattern.compile(myRegex);

Matcher myMatcher = myPattern.matcher(myTestString);

String myGroup = “”;

System.out.println(“The test string was: ‘“ + myTestString + “‘.”); System.out.println(“The regular expression was ‘“ + myRegex + “‘.”); while (myMatcher.find())

{

myGroup = myMatcher.group();

System.out.println(“A match ‘“ + myGroup + “‘ was found.”); } // end while

if (myGroup == “”){

System.out.println(“There were no matches.”);

}// end if

}// end main()

}

2.Save the code as Find_the.java.

3.At the command line, type the command javac Find_the.java to compile the source code into a class file.

4.At the command line, type the command java Find_the to run the code, and inspect the results, as shown in Figure 25-1.

622

Regular Expressions in Java

Figure 25-1

How It Works

The Java compiler, javac, is used to compile the code. Be sure to type the filename correctly, including the

.java file suffix, or the code most likely won’t compile.

The Java interpreter, java, is used to run the code.

To be able to conveniently use the classes of the java.util.regex package, it is customary to import the package into your code:

import java.util.regex.*;

This enables the developer to write code such as the following:

Pattern myPattern = Pattern.compile(myRegex);

If there were no import statement, it would be necessary to write the fully qualified name of the Pattern class in each line of code, as follows:

java.util.regex.Pattern myPattern = java.util.regex.Pattern.compile(myRegex);

Even in simple code like this, the readability benefit of the shorter lines should be clear to you.

The test string is specified and assigned to the myTestString variable:

String myTestString = “The theatre is the greatest form of live entertainment

according to thespians.”;

A string value is assigned to the regex variable:

String myRegex = “the[a-z]*\\b”;

The way in which you write the regular expression pattern is different from the syntax needed in the programs and languages you have seen so far in this book. The \b metacharacter matches the position between a word character and a nonword character. However, to convey to the Java compiler that you intend \b, you need to escape the initial backslash character and write \\b.

623

Chapter 25

If you attempt to declare the myRegex variable and assign it a value as follows:

String myRegex = “the[a-z]*\b”;

the result will not be what you expect. The \b will be interpreted as a backspace character. Figure 25-2 shows the result if you compile and run the Java code in the file UnescapedFind_the.java.

Figure 25-2

The myPattern variable is declared as a Pattern object that is created by using the compile() method with the myRegex variable as its argument:

Pattern myPattern = Pattern.compile(myRegex);

A myMatcher variable, which is a Matcher object, is declared and assigned the object created by using the myPattern object’s matcher() method with the myTestString variable as its argument. There is no public constructor for a Matcher object, so if you want to create a Matcher object, you must use the technique shown:

Matcher myMatcher = myPattern.matcher(myTestString);

The value of the test string contained in the myTestString variable and the regular expression contained in the myRegex variable are displayed using the println() method of System.out:

System.out.println(“The test string was ‘“ + myTestString + “‘.”);

System.out.println(“The regular expression was: ‘“ + myRegex + “‘.”);

Then a while loop is used to test whether or not there are any matches. If there is a match, the value returned by myMatcher.find() is true. Therefore, the code contained in the while loop is executed for each match found:

while (myMatcher.find())

{

The value returned by the group() method is assigned to the myGroup variable:

myGroup = myMatcher.group();

And the println() method is used to display the value of the match that is found during the present iteration of the while loop:

System.out.println(“A match ‘“ + myGroup + “‘ was found.”);

} // end while

624

Regular Expressions in Java

If no match is found, the value of the myGroup variable is the empty string, and then a message is displayed using the println() method to indicate that no matches have been found:

if (myGroup == “”){

System.out.println(“There were no matches.”); } // end if

The effect of the code just described is to display each occurrence in the test string of a character sequence beginning with the.

If you review the value of the myTestString variable, you will see that there are four possible occurrences of the character sequence the in the test string: The, theatre, the, and thespians.

String myTestString = “The theatre is the greatest form of live entertainment

according to thespians.”;

Matching in Java is, by default, case sensitive, so the character sequence The is not a match, because the first character is an uppercase alphabetic character.

However, the word theatre matches. The pattern component [a-z]* matches the character sequence atre. The word the matches. The pattern component [a-z]* matches zero characters. And the word thespians matches. The pattern component [a-z]* matches the character sequence spians.

The second example uses a text file to hold the regular expression pattern and another text file to hold the test text.

Try It Out

Retrieving Data from a File

1.Type the following code in a text editor:

import java.io.*;

import java.util.regex.*;

public final class RegexTester { private static String myRegex; private static String testString;

private static BufferedReader myPatternBufferedReader; private static BufferedReader myTestStringBufferedReader; private static Pattern myPattern;

private static Matcher myMatcher; private static boolean foundOrNot;

public static void main(String[] argv) { findFiles();

doMatching(); tidyUp(); }

private static void findFiles() { try {

myPatternBufferedReader = new BufferedReader(new FileReader(“Pattern.txt”));

}

catch (FileNotFoundException fnfe) {

System.out.println(“Cannot find the Pattern input file! “+fnfe.getMessage());

625

Chapter 25

System.exit(0); }

try { myRegex = myPatternBufferedReader.readLine();

}

catch (IOException ioe) {}

// Find and open the file containing the test text try {

myTestTextBufferedReader = new BufferedReader(new FileReader(“TestText.txt”));

}

catch (FileNotFoundException fnfe) {

System.out.println(“Cannot locate Test Text input file! “+fnfe.getMessage()); System.exit(0); }

try {

testString = myTestTextBufferedReader.readLine();

}

catch (IOException ioe) {}

myPattern = Pattern.compile(myRegex); myMatcher = myPattern.matcher(testString);

System.out.println(“The regular expression is: “ + myRegex); System.out.println(“The test text is: “ + testString);

} // end of findFiles()

private static void doMatching()

{

while(myMatcher.find())

{

System.out.println(“The text \””

+myMatcher.group() + “\” was found, starting at index “

+myMatcher.start() + “ and ending at index “

+myMatcher.end() + “.”);

foundOrNot = true; }

if(!foundOrNot){ System.out.println(“No match was found.”);

}

}// end of doMatching()

private static void tidyUp()

{

try{

myPatternBufferedReader.close();

myTestTextBufferedReader.close(); }catch(IOException ioe){}

}// end of tidyUp()

}

2.Save the code as RegexTester.java; to compile the code, type javac RegexTester.java at the command line.

3.Type the following code in a text editor, and save it as Pattern.txt:

\d\w

Then type the following code in a text editor, and save it as TestText.txt.

3D 2A 5R

626

Regular Expressions in Java

4.Run the code by typing java RegexTester at the command line. Notice in Figure 25-3 that each of the three character sequences in TestText.txt is matched.

Figure 25-3

How It Works

This example performs file access, so you need to import the java.io package as well as the java.util.regex package:

import java.io.*;

import java.util.regex.*;

As assortment of variables is declared, each of which is used later in the code:

private static String myRegex; private static String testString;

private static BufferedReader myPatternBufferedReader; private static BufferedReader myTestTextBufferedReader; private static Pattern myPattern;

private static Matcher myMatcher; private static boolean foundOrNot;

The main() method consists of three methods: findFiles(), doMatching(), and tidyUp().

public static void main(String[] argv) { findFiles();

doMatching(); tidyUp(); }

The findFiles() method uses a try . . . catch block to test whether the file Pattern.txt exists:

private static void findFiles() { try {

myPatternBufferedReader = new BufferedReader(new FileReader(“Pattern.txt”));

}

If it doesn’t exist, an error message is displayed, and the program terminates:

catch (FileNotFoundException fnfe) {

System.out.println(“Cannot find the Pattern input file! “+fnfe.getMessage()); System.exit(0); }

627

Chapter 25

If the file Pattern.txt is found (meaning that no error interrupts program flow), the myPattern BufferedReader object’s readLine() method (which instantiates the BufferedReader class) is used to read in one line of Pattern.txt and assign the text in that first line to the myRegex variable:

try { myRegex = myPatternBufferedReader.readLine();

The myTestTextBufferedReader object is used to process the test text file, TestText.txt, in a similar way. The content of its first line is assigned to the testString variable.

Having read in values for the myRegex and testString variables, a Pattern object, myPattern, is created using the Pattern class’s compile() method:

myPattern = Pattern.compile(myRegex);

Then the myPattern object’s matcher() method is used to create a Matcher object, myMatcher:

myMatcher = myPattern.matcher(testString);

The findFiles() method is completed by displaying the values of the myRegex and testString variables, which confirms successful loading of both files:

System.out.println(“The regular expression is: “ + myRegex); System.out.println(“The test text is: “ + testString);

}

Then the doMatching() method is executed:

private static void doMatching()

{

It uses a while loop to process each match found:

while(myMatcher.find())

{

For each match, the group(), start(), and end() methods of the myMatcher object are used to display the match, where it starts, and where it ends, respectively:

System.out.println(“The text \””

+myMatcher.group() + “\” was found, starting at index “

+myMatcher.start() + “ and ending at index “

+myMatcher.end() + “.”);

If any match is found, the value of the foundOrNot variable is set to true in the final line of the while loop:

foundOrNot = true; }

628