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

Chapter 25

Escaped Character Sequence

Matches

\+

+ (plus sign)

\.

. (period character)

There is an alternative way to use a metacharacter without having to escape it in the way shown in the preceding table. A metacharacter or sequence of metacharacters can be enclosed between two other metacharacters: \Q (which starts a sequence of quoted characters) and \E (which ends a sequence of quoted characters).

Using Methods of the String Class

Several methods of the String class support the use of regular expression functionality. The matches() method tests whether there is a match in the string for a regular expression pattern. The replaceFirst() and replaceAll() methods replace one or all substrings that match a regular expression with a specified replacement string. The String class also has a replace() method, but it makes no use of regular expression functionality, simply matching and replacing a literal string.

The following table summarizes information about the methods of the String class that support regular expression functionality. There are, of course, many other methods of the String class that do not use regular expressions; they are not discussed here.

Method

Description

 

 

matches()

Tests whether or not a string contains a match for a given regular

 

expression

replaceFirst()

Replaces the first substring in the string that matches a regular expres-

 

sion pattern with the specified replacement string

replaceAll()

Replaces all substrings in the string that match a regular expression

 

pattern with the specified replacement string

split()

Splits a string into substrings at each match for a specified regular

 

expression

Using the matches() Method

The String class’s matches() method tests whether the whole string matches a regular expression. The matches() method takes a single argument, which is a String representing the regular expression pattern.

654

Regular Expressions in Java

Try It Out

The matches() Method of the String Class

1.Type the following code in a text editor:

import java.util.regex.*;

public class stringMatches{

public static void main(String args[]){ findMatch(args[0]);

} // end main()

public static boolean findMatch(String testString){ String myRegex = “\\b[a-z]*hip[a-z]*\\b”;

boolean testResult = testString.matches(myRegex);

System.out.println(“The string was: “ + testString); System.out.println(“The regular expression pattern was:” + myRegex); if (testResult)

{

System.out.println(“There was a match.”); } // end if

else

{

System.out.println(“There was no match.”);

}

return true; } // findMatch()

}

2.Save the code as stringMatches.java.

3.Compile the code. At the command line, type javac stringMatches.java.

4.Run the code. At the command line, type java stringMatches “ship”, and inspect the displayed results.

5.Run the code again. At the command line, type java stringMatches “The ship was large.” Inspect the results, as shown in Figure 25-13. Notice that the character sequence ship matches, but the character sequence The ship was large. does not match.

Figure 25-13

655

Chapter 25

How It Works

The regular expression pattern assigned to the myRegex variable matches any word containing the character sequence hip:

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

The String class’s matches() method is used to assign a value to the boolean variable testResult. Notice that the matches() method’s argument is the regular expression assigned to the myRegex variable:

boolean testResult = testString.matches(myRegex);

Because the matches() method simply returns a boolean value, you are confined to testing the value of the testResult variable to see if it is true or false. In this example, the value of the testResult variable is used to control the display of a message indicating whether or not there is a match:

if (testResult)

{

System.out.println(“There was a match.”); } // end if

else

{

System.out.println(“There was no match.”);

}

Because the pattern \b[a-z]*hip[a-z]*\b matches case sensitively, it will match the character sequence ship but not Ship, for example. Because the String class’s matches() method must match the whole string, the pattern will not match strings such as The ship was large., which contain other characters in addition to the character sequence that would match the pattern in other circumstances.

Using the replaceFirst() Method

The String class’s replaceFirst() method takes two arguments. The first argument is a String containing the regular expression pattern. The second argument is a String containing the replacement string.

The replaceFirst() method can throw a PatternSyntaxException if there is an error in the regular expression pattern.

The following example uses the replaceFirst() method to replace the first occurrence of the character sequence twinkle with the character sequence TWINKLE.

Try It Out

Using the String Class’s replaceFirst() Method

1.Type the following code in a text editor:

import java.util.regex.*;

public class stringReplaceFirst{

public static void main(String args[]){ myReplaceFirst(args[0]);

656

Regular Expressions in Java

} // end main()

public static boolean myReplaceFirst(String testString){ String myRegex = “twinkle”;

String testResult = testString.replaceFirst(myRegex, “TWINKLE”);

System.out.println(“The string was: ‘“ + testString + “‘.”); System.out.println(“The regular expression pattern was: ‘“ + myRegex +”’.”); System.out.println(“After replacement the string was: ‘“ + testResult +”’.”);

return true; } // myReplaceFirst()

}

2.Save the code as stringReplaceFirst.java.

3.Compile the code. At the command line, type javac stringReplaceFirst.java.

4.Run the code. At the command line, type java stringReplaceFirst “twinkle, twinkle little star”, and inspect the displayed results, as shown in Figure 25-14.

Figure 25-14

How It Works

A simple literal pattern, twinkle, is assigned to the myRegex variable:

String myRegex = “twinkle”;

The replaceFirst() method is used to assign a value to the testResult variable, which is a String. The second argument of the replaceFirst() method specifies that the character sequence TWINKLE is the replacement string:

String testResult = testString.replaceFirst(myRegex, “TWINKLE”);

The value of the string, the regular expression, and the replaced string are displayed:

System.out.println(“The string was: ‘“ + testString + “‘.”); System.out.println(“The regular expression pattern was: ‘“ + myRegex +”’.”); System.out.println(“After replacement the string was: ‘“ + testResult +”’.”);

The value of testString was twinkle, twinkle little star. The first occurrence of twinkle is replaced. So after replacement, the string is TWINKLE, twinkle little star..

657