- •Introduction
- •Who This Book Is For
- •What This Book Covers
- •How This Book Is Structured
- •What You Need to Use This Book
- •Conventions
- •Source Code
- •Errata
- •p2p.wrox.com
- •What Are Regular Expressions?
- •What Can Regular Expressions Be Used For?
- •Finding Doubled Words
- •Checking Input from Web Forms
- •Changing Date Formats
- •Finding Incorrect Case
- •Adding Links to URLs
- •Regular Expressions You Already Use
- •Search and Replace in Word Processors
- •Directory Listings
- •Online Searching
- •Why Regular Expressions Seem Intimidating
- •Compact, Cryptic Syntax
- •Whitespace Can Significantly Alter the Meaning
- •No Standards Body
- •Differences between Implementations
- •Characters Change Meaning in Different Contexts
- •Regular Expressions Can Be Case Sensitive
- •Case-Sensitive and Case-Insensitive Matching
- •Case and Metacharacters
- •Continual Evolution in Techniques Supported
- •Multiple Solutions for a Single Problem
- •What You Want to Do with a Regular Expression
- •Replacing Text in Quantity
- •Regular Expression Tools
- •findstr
- •Microsoft Word
- •StarOffice Writer/OpenOffice.org Writer
- •Komodo Rx Package
- •PowerGrep
- •Microsoft Excel
- •JavaScript and JScript
- •VBScript
- •Visual Basic.NET
- •Java
- •Perl
- •MySQL
- •SQL Server 2000
- •W3C XML Schema
- •An Analytical Approach to Using Regular Expressions
- •Express and Document What You Want to Do in English
- •Consider the Regular Expression Options Available
- •Consider Sensitivity and Specificity
- •Create Appropriate Regular Expressions
- •Document All but Simple Regular Expressions
- •Document What You Expect the Regular Expression to Do
- •Document What You Want to Match
- •Test the Results of a Regular Expression
- •Matching Single Characters
- •Matching Sequences of Characters That Each Occur Once
- •Introducing Metacharacters
- •Matching Sequences of Different Characters
- •Matching Optional Characters
- •Matching Multiple Optional Characters
- •Other Cardinality Operators
- •The * Quantifier
- •The + Quantifier
- •The Curly-Brace Syntax
- •The {n} Syntax
- •The {n,m} Syntax
- •Exercises
- •Regular Expression Metacharacters
- •Thinking about Characters and Positions
- •The Period (.) Metacharacter
- •Matching Variably Structured Part Numbers
- •Matching a Literal Period
- •The \w Metacharacter
- •The \W Metacharacter
- •Digits and Nondigits
- •The \d Metacharacter
- •Canadian Postal Code Example
- •The \D Metacharacter
- •Alternatives to \d and \D
- •The \s Metacharacter
- •Handling Optional Whitespace
- •The \S Metacharacter
- •The \t Metacharacter
- •The \n Metacharacter
- •Escaped Characters
- •Finding the Backslash
- •Modifiers
- •Global Search
- •Case-Insensitive Search
- •Exercises
- •Introduction to Character Classes
- •Choice between Two Characters
- •Using Quantifiers with Character Classes
- •Using the \b Metacharacter in Character Classes
- •Selecting Literal Square Brackets
- •Using Ranges in Character Classes
- •Alphabetic Ranges
- •Use [A-z] With Care
- •Digit Ranges in Character Classes
- •Hexadecimal Numbers
- •IP Addresses
- •Reverse Ranges in Character Classes
- •A Potential Range Trap
- •Finding HTML Heading Elements
- •Metacharacter Meaning within Character Classes
- •The ^ metacharacter
- •How to Use the - Metacharacter
- •Negated Character Classes
- •Combining Positive and Negative Character Classes
- •POSIX Character Classes
- •The [:alnum:] Character Class
- •Exercises
- •String, Line, and Word Boundaries
- •The ^ Metacharacter
- •The ^ Metacharacter and Multiline Mode
- •The $ Metacharacter
- •The $ Metacharacter in Multiline Mode
- •Using the ^ and $ Metacharacters Together
- •Matching Blank Lines
- •Working with Dollar Amounts
- •Revisiting the IP Address Example
- •What Is a Word?
- •Identifying Word Boundaries
- •The \< Syntax
- •The \>Syntax
- •The \b Syntax
- •The \B Metacharacter
- •Less-Common Word-Boundary Metacharacters
- •Exercises
- •Grouping Using Parentheses
- •Parentheses and Quantifiers
- •Matching Literal Parentheses
- •U.S. Telephone Number Example
- •Alternation
- •Choosing among Multiple Options
- •Unexpected Alternation Behavior
- •Capturing Parentheses
- •Numbering of Captured Groups
- •Numbering When Using Nested Parentheses
- •Named Groups
- •Non-Capturing Parentheses
- •Back References
- •Exercises
- •Why You Need Lookahead and Lookbehind
- •The (? metacharacters
- •Lookahead
- •Positive Lookahead
- •Negative Lookahead
- •Positive Lookahead Examples
- •Positive Lookahead in the Same Document
- •Inserting an Apostrophe
- •Lookbehind
- •Positive Lookbehind
- •Negative Lookbehind
- •How to Match Positions
- •Adding Commas to Large Numbers
- •Exercises
- •What Are Sensitivity and Specificity?
- •Extreme Sensitivity, Awful Specificity
- •Email Addresses Example
- •Replacing Hyphens Example
- •The Sensitivity/Specificity Trade-Off
- •Sensitivity, Specificity, and Positional Characters
- •Sensitivity, Specificity, and Modes
- •Sensitivity, Specificity, and Lookahead and Lookbehind
- •How Much Should the Regular Expressions Do?
- •Abbreviations
- •Characters from Other Languages
- •Names
- •Sensitivity and How to Achieve It
- •Specificity and How to Maximize It
- •Exercises
- •Documenting Regular Expressions
- •Document the Problem Definition
- •Add Comments to Your Code
- •Making Use of Extended Mode
- •Know Your Data
- •Abbreviations
- •Proper Names
- •Incorrect Spelling
- •Creating Test Cases
- •Debugging Regular Expressions
- •Treacherous Whitespace
- •Backslashes Causing Problems
- •Considering Other Causes
- •The User Interface
- •Metacharacters Available
- •Quantifiers
- •The @ Quantifier
- •The {n,m} Syntax
- •Modes
- •Character Classes
- •Back References
- •Lookahead and Lookbehind
- •Lazy Matching versus Greedy Matching
- •Examples
- •Character Class Examples, Including Ranges
- •Whole Word Searches
- •Search-and-Replace Examples
- •Changing Name Structure Using Back References
- •Manipulating Dates
- •The Star Training Company Example
- •Regular Expressions in Visual Basic for Applications
- •Exercises
- •The User Interface
- •Metacharacters Available
- •Quantifiers
- •Modes
- •Character Classes
- •Alternation
- •Back References
- •Lookahead and Lookbehind
- •Search Example
- •Search-and-Replace Example
- •Online Chats
- •POSIX Character Classes
- •Matching Numeric Digits
- •Exercises
- •Introducing findstr
- •Finding Literal Text
- •Quantifiers
- •Character Classes
- •Command-Line Switch Examples
- •The /v Switch
- •The /a Switch
- •Single File Examples
- •Simple Character Class Example
- •Find Protocols Example
- •Multiple File Example
- •A Filelist Example
- •Exercises
- •The PowerGREP Interface
- •A Simple Find Example
- •The Replace Tab
- •The File Finder Tab
- •Syntax Coloring
- •Other Tabs
- •Numeric Digits and Alphabetic Characters
- •Quantifiers
- •Back References
- •Alternation
- •Line Position Metacharacters
- •Word-Boundary Metacharacters
- •Lookahead and Lookbehind
- •Longer Examples
- •Finding HTML Horizontal Rule Elements
- •Matching Time Example
- •Exercises
- •The Excel Find Interface
- •Escaping Wildcard Characters
- •Using Wildcards in Data Forms
- •Using Wildcards in Filters
- •Exercises
- •Using LIKE with Regular Expressions
- •The % Metacharacter
- •The _ Metacharacter
- •Character Classes
- •Negated Character Classes
- •Using Full-Text Search
- •Using The CONTAINS Predicate
- •Document Filters on Image Columns
- •Exercises
- •Using the _ and % Metacharacters
- •Testing Matching of Literals: _ and % Metacharacters
- •Using Positional Metacharacters
- •Using Character Classes
- •Quantifiers
- •Social Security Number Example
- •Exercises
- •The Interface to Metacharacters in Microsoft Access
- •Creating a Hard-Wired Query
- •Creating a Parameter Query
- •Using the ? Metacharacter
- •Using the * Metacharacter
- •Using the # Metacharacter
- •Using the # Character with Date/Time Data
- •Using Character Classes in Access
- •Exercises
- •The RegExp Object
- •Attributes of the RegExp Object
- •The Other Properties of the RegExp Object
- •The test() Method of the RegExp Object
- •The exec() Method of the RegExp Object
- •The String Object
- •Metacharacters in JavaScript and JScript
- •SSN Validation Example
- •Exercises
- •The RegExp Object and How to Use It
- •Quantifiers
- •Positional Metacharacters
- •Character Classes
- •Word Boundaries
- •Lookahead
- •Grouping and Nongrouping Parentheses
- •Exercises
- •The System.Text.RegularExpressions namespace
- •A Simple Visual Basic .NET Example
- •The Classes of System.Text.RegularExpressions
- •The Regex Object
- •Using the Match Object and Matches Collection
- •Using the Match.Success Property and Match.NextMatch Method
- •The GroupCollection and Group Classes
- •The CaptureCollection and Capture Class
- •The RegexOptions Enumeration
- •Case-Insensitive Matching: The IgnoreCase Option
- •Multiline Matching: The Effect on the ^ and $ Metacharacters
- •Right to Left Matching: The RightToLeft Option
- •Lookahead and Lookbehind
- •Exercises
- •An Introductory Example
- •The Classes of System.Text.RegularExpressions
- •The Regex Class
- •The Options Property of the Regex Class
- •Regex Class Methods
- •The CompileToAssembly() Method
- •The GetGroupNames() Method
- •The GetGroupNumbers() Method
- •GroupNumberFromName() and GroupNameFromNumber() Methods
- •The IsMatch() Method
- •The Match() Method
- •The Matches() Method
- •The Replace() Method
- •The Split() Method
- •Using the Static Methods of the Regex Class
- •The IsMatch() Method as a Static
- •The Match() Method as a Static
- •The Matches() Method as a Static
- •The Replace() Method as a Static
- •The Split() Method as a Static
- •The Match and Matches Classes
- •The Match Class
- •The GroupCollection and Group Classes
- •The RegexOptions Class
- •The IgnorePatternWhitespace Option
- •Metacharacters Supported in Visual C# .NET
- •Using Named Groups
- •Using Back References
- •Exercise
- •The ereg() Set of Functions
- •The ereg() Function
- •The ereg() Function with Three Arguments
- •The eregi() Function
- •The ereg_replace() Function
- •The eregi_replace() Function
- •The split() Function
- •The spliti() Function
- •The sql_regcase() Function
- •Perl Compatible Regular Expressions
- •Pattern Delimiters in PCRE
- •Escaping Pattern Delimiters
- •Matching Modifiers in PCRE
- •Using the preg_match() Function
- •Using the preg_match_all() Function
- •Using the preg_grep() Function
- •Using the preg_quote() Function
- •Using the preg_replace() Function
- •Using the preg_replace_callback() Function
- •Using the preg_split() Function
- •Supported Metacharacters with ereg()
- •Using POSIX Character Classes with PHP
- •Supported Metacharacters with PCRE
- •Positional Metacharacters
- •Character Classes in PHP
- •Documenting PHP Regular Expressions
- •Exercises
- •W3C XML Schema Basics
- •Tools for Using W3C XML Schema
- •Comparing XML Schema and DTDs
- •How Constraints Are Expressed in W3C XML Schema
- •W3C XML Schema Datatypes
- •Derivation by Restriction
- •Unicode and W3C XML Schema
- •Unicode Overview
- •Using Unicode Character Classes
- •Matching Decimal Numbers
- •Mixing Unicode Character Classes with Other Metacharacters
- •Unicode Character Blocks
- •Using Unicode Character Blocks
- •Metacharacters Supported in W3C XML Schema
- •Positional Metacharacters
- •Matching Numeric Digits
- •Alternation
- •Using the \w and \s Metacharacters
- •Escaping Metacharacters
- •Exercises
- •Introduction to the java.util.regex Package
- •Obtaining and Installing Java
- •The Pattern Class
- •Using the matches() Method Statically
- •Two Simple Java Examples
- •The Properties (Fields) of the Pattern Class
- •The CASE_INSENSITIVE Flag
- •Using the COMMENTS Flag
- •The DOTALL Flag
- •The MULTILINE Flag
- •The UNICODE_CASE Flag
- •The UNIX_LINES Flag
- •The Methods of the Pattern Class
- •The compile() Method
- •The flags() Method
- •The matcher() Method
- •The matches() Method
- •The pattern() Method
- •The split() Method
- •The Matcher Class
- •The appendReplacement() Method
- •The appendTail() Method
- •The end() Method
- •The find() Method
- •The group() Method
- •The groupCount() Method
- •The lookingAt() Method
- •The matches() Method
- •The pattern() Method
- •The replaceAll() Method
- •The replaceFirst() Method
- •The reset() Method
- •The start() Method
- •The PatternSyntaxException Class
- •Using the \d Metacharacter
- •Character Classes
- •The POSIX Character Classes in the java.util.regex Package
- •Unicode Character Classes and Character Blocks
- •Using Escaped Characters
- •Using Methods of the String Class
- •Using the matches() Method
- •Using the replaceFirst() Method
- •Using the replaceAll() Method
- •Using the split() Method
- •Exercises
- •Obtaining and Installing Perl
- •Creating a Simple Perl Program
- •Basics of Perl Regular Expression Usage
- •Using the m// Operator
- •Using Other Regular Expression Delimiters
- •Matching Using Variable Substitution
- •Using the s/// Operator
- •Using s/// with the Global Modifier
- •Using s/// with the Default Variable
- •Using the split Operator
- •Using Quantifiers in Perl
- •Using Positional Metacharacters
- •Captured Groups in Perl
- •Using Back References in Perl
- •Using Alternation
- •Using Character Classes in Perl
- •Using Lookahead
- •Using Lookbehind
- •Escaping Metacharacters
- •A Simple Perl Regex Tester
- •Exercises
- •Index
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