Escape Regex.replace() replacement string in VB.ne

2019-09-13 23:43发布

问题:

I want to use Regex.replace(input As String, pattern As String, replacement As String) in VB.net. The replacement string can contain substitutions of the form $1 or ${test}.

I need to call this with replacements I have no control over. So I'd like to escape all substitutions in my replacement strings. Java has Matcher.quoteReplacement() to do exactly that job.

  • Is there a Regex.quoteReplacement(replacement As String) As String or similar that escapes all substitutions in the given string?
  • Can I turn substitutions off?
  • Is there some alternative I could use instead?

  • MSDN for Regex.replace()
  • MSDN for substitutions
  • JavaDoc for Matcher.quoteReplacement()

回答1:

A possible solution that works in simple cases is:

Function quoteReplacement(text As String) As String
    Return Regex.Replace(text, "\$", "$$$$")
End Function

But I'm not at all sure that works in all corner cases there might be.