Speed up Kernel::System::TemplateGenerator

When replying to an email of size 3.2MB, AgentTicketCompose
spent nearly 44s in Kernel::System::TemplateGenerator->_Replace.
This patch reduces the time to about 11s on my dev system.

As an added bonus, it reduces the code size and removes
code duplication.