Unlike
Pattern objects, Matcher objects record state information. Occasionally, you might want to reset a matcher to clear that information after performing a pattern match. The following methods reset a matcher: - public Matcher reset()
:resets a matcher's state, including the matcher's append position (which clears to 0). The next pattern match operation begins at the start of the matcher's text. A reference to the currentMatcherobject returns. Example:m.reset ();resets the matcher referenced bym. - public Matcher reset(CharSequence text)
:resets a matcher's state and sets the matcher's text totext's contents. The next pattern match operation begins at the start of the matcher's new text. A reference to the currentMatcherobject returns. Example:m.reset ("new text");resets them-referenced matcher and also specifiesnew textas the matcher's new text.
StringBuffer object. The following methods use the append position: - public Matcher appendReplacement(StringBuffer sb, String replacement)
:reads the matcher's text characters and appends them to thesb-referencedStringBufferobject. The method stops reading after the last character preceding the previous pattern match. This method next appends the characters in thereplacement-referencedStringobject to theStringBufferobject. (The replacement string may contain references to text sequences captured during the previous match, via dollar-sign characters ($) and capturing group numbers.) Finally, the method sets the matcher's append position to the index of the last matched character plus one. A reference to the current matcher returns. This method throws anIllegalStateExceptionobject if the matcher has not yet made a match or if the previous match attempt failed. AnIndexOutOfBoundsExceptionobject is thrown ifreplacementspecifies a capturing group that does not exist in the pattern. - public StringBuffer appendTail(StringBuffer sb)
:appends all text to theStringBufferobject and returns that object's reference. Following a final call to theappendReplacement(StringBuffer sb, String replacement)method, callappendTail(StringBuffer sb)to copy remaining text to theStringBufferobject.
appendReplacement(StringBuffer sb, String replacement) and appendTail(StringBuffer sb) methods to replace all occurrences of cat within one cat, two cats, or three cats on a fence with caterpillar. A capturing group and a reference to that capturing group in the replacement text allows the insertion of erpillar after each cat match: Pattern p = Pattern.compile ("(cat)");Matcher m = p.matcher ("one cat, two cats, or three cats on a fence");StringBuffer sb = new StringBuffer ();
while (m.find ())
m.appendReplacement (sb, "erpillar");m.appendTail (sb);
System.out.println (sb);
No comments:
Post a Comment