Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
This section describes how to use the methods of theMatcher
class we have not yet covered. For convenience, the methods listed below are grouped according to functionality.Index Methods
Index methods provide useful index values that show precisely where the match was found in the input string:Study Methods
Study methods review the input string and return a boolean indicating whether or not the pattern is found.
public boolean lookingAt()
public boolean find()
public boolean find(int start)
public boolean matches()
Replacement Methods
Replacement methods are useful methods for replacing text in an input string.
public Matcher appendReplacement(StringBuffer sb, String replacement)
public StringBuffer appendTail(StringBuffer sb)
public String replaceAll(String replacement)
public String replaceFirst(String replacement)
Using the
Here's an example,start
andend
MethodsMatcherTest
, that counts the number of times the word "dog" appears in the input string.You can see that this example uses word boundaries to ensure that the lettersimport java.util.regex.*; public final class MatcherTest { private static final String REGEX = "\\bdog\\b"; private static final String INPUT = "dog dog dog doggie dogg"; public static void main(String[] argv) { Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); // get a matcher object int count = 0; while(m.find()) { count++; System.out.println("Match number "+count); System.out.println("start(): "+m.start()); System.out.println("end(): "+m.end()); } } } OUTPUT: Match number 1 start(): 0 end(): 3 Match number 2 start(): 4 end(): 7 Match number 3 start(): 8 end(): 11"d" "o" "g"
are not merely a substring in a longer word. It also gives some useful information about where in the input string the match has occurred. Thestart
method returns the start index of the subsequence captured by the given group during the previous match operation, andend
returns the index of the last character matched, plus one.Using the
Thematches
andlookingAt
Methodsmatches
andlookingAt
methods both attempt to match an input sequence against a pattern. The difference, however, is thatmatches
requires the entire input sequence to be matched, whilelookingAt
does not. Both methods always start at the beginning of the input string. Here's the full code,MatchesLooking
:import java.util.regex.*; public final class MatchesLooking { private static final String REGEX = "foo"; private static final String INPUT = "fooooooooooooooooo"; private static Pattern pattern; private static Matcher matcher; public static void main(String[] argv) { // Initialize pattern = Pattern.compile(REGEX); matcher = pattern.matcher(INPUT); System.out.println("Current REGEX is: "+REGEX); System.out.println("Current INPUT is: "+INPUT); System.out.println("lookingAt(): "+matcher.lookingAt()); System.out.println("matches(): "+matcher.matches()); } } Current REGEX is: foo Current INPUT is: fooooooooooooooooo lookingAt(): true matches(): falseUsing
ThereplaceFirst(String)
andreplaceAll(String)
replaceFirst
andreplaceAll
methods replace text that matches a given regular expression. As their names indicate,replaceFirst
replaces the first occurrence, andreplaceAll
replaces all occurences. Here's theReplaceTest
code:In this first version, all occurrences of "dog" are replaced with "cat". But why stop here? Rather than replace a simple literal like "dog", you can replace text that matches any regular expression. The API for this method states that "given the regular expression a*b, the input 'aabfooaabfooabfoob', and the replacement string '-', an invocation of this method on a matcher for that expression would yield the string '-foo-foo-foo-'."public final class ReplaceTest { private static String REGEX = "dog"; private static String INPUT = "The dog says meow. All dogs say meow."; private static String REPLACE = "cat"; public static void main(String[] argv) { Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); // get a matcher object INPUT = m.replaceAll(REPLACE); System.out.println(INPUT); } } OUTPUT: The cat says meow. All cats say meow.Here's the code,
ReplaceTest2
:To replace only the first occurrence of the pattern, simply callimport java.util.regex.*; public final class ReplaceTest2 { private static String REGEX = "a*b"; private static String INPUT = "aabfooaabfooabfoob"; private static String REPLACE = "-"; public static void main(String[] argv) { Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); // get a matcher object INPUT = m.replaceAll(REPLACE); System.out.println(INPUT); } } OUTPUT: -foo-foo-foo-replaceFirst
instead ofreplaceAll
. It accepts the same parameter.The
appendReplacement(StringBuffer,String)
andappendTail(StringBuffer)
The
Matcher
class also providesappendReplacement
andappendTail
methods for text replacement. Here's an example that uses these two methods to achieve the same effect asreplaceAll
.import java.util.regex.*; public final class RegexTest { private static String REGEX = "a*b"; private static String INPUT = "aabfooaabfooabfoob"; private static String REPLACE = "-"; public static void main(String[] argv) { Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); // get a matcher object StringBuffer sb = new StringBuffer(); while(m.find()){ m.appendReplacement(sb,REPLACE); } m.appendTail(sb); System.out.println(sb.toString()); } } OUTPUT: -foo-foo-foo-For convenience, the
Matcher
Method Equivalents injava.lang.String
String
class mimics a couple ofMatcher
methods as well:
public String replaceFirst(String regex, String replacement)
: Replaces the first substring of this string that matches the given regular expression with the given replacement. An invocation of this method of the formstr.replaceFirst(regex, repl)
yields exactly the same result as the expressionPattern.compile(regex).matcher(str).replaceFirst(repl)
public String replaceAll(String regex, String replacement)
: Replaces each substring of this string that matches the given regular expression with the given replacement. An invocation of this method of the formstr.replaceAll(regex, repl)
yields exactly the same result as the expressionPattern.compile(regex).matcher(str).replaceAll(repl)
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.