// Method for replacing a single pattern and a single replacement text
Public static int substitute (stringbuffer result,
Patternmatcher, pattern,
Substitution sub, patternmatcherinput input,
Int numsubs)
{
Int beginoffset, subcount;
Char [] inputbuffer;
Subcount = 0;
Beginoffset = input. getbeginoffset ();
// The following method copies the input and saves it as inputbuffer.
Inputbuffer = input. getbuffer ();
// Must be! = 0 because substitute_all is represented by-1.
// Do not change to numsubs> 0.
While (numsubs! = 0 & matcher. Contains (input, pattern )){
-- Numsubs;
++ Subcount;
// Copy the content in the original text that does not need to be replaced to the result directly.
Result. append (inputbuffer, beginoffset,
Input. getmatchbeginoffset ()-beginoffset );
// Replace the content matched in the original text and save the content to the result.
Sub. appendsubstitution (result, matcher. getmatch (), subcount,
Input, matcher, pattern );
// Update the start position of the next loop. The matched position is no longer retrieved.
Beginoffset = input. getmatchendoffset ();
}
// Copy the last unmatched content in the original text to the result
Result. append (inputbuffer, beginoffset, input. Length ()-beginoffset );
Return subcount;
}
}