At first glance, Pattern.quote seems to be doing the job.
However, looking at the detail of your question, it seems that you want / expect that you can avoid some metacharacters, not others. Pattern.quote will not do this if you apply it to a single line. Rather, he will quote each character. (He does not use a backslash to write. He uses "\ E" and "\ Q". \, Which carefully avoids the cost of parsing the string to find the characters to be escaped.)
But the real problem is that you did not say how the quotation mark should decide which metacharacters to escape and which of them to leave unchanged. For example, as you know, to avoid the first three characters, but not "."?
Without a clearer specification, your question is pretty much incontrovertible. And even with the specification, there is little chance of finding an easy way to do this.
IMO, the best approach would be to do escaping before assembling a template from its constituent parts ... assuming what happens here.
source share