Regular expression involving double-quotes

  • Thread starter Thread starter shabbs
  • Start date Start date
S

shabbs

I'm having a heck of a time trying to get this to work:

Regex.Replace(input, "(?<esc>['""\])", "\${esc}")

What I'd like is to take any ' (single-quote), " (double-quote) and \
(backslash) and prepend it with a backslash.

It works great for the single-quote and the backslash, but the double-
quote just seems to get dropped from the string altogether. I've also
tried replacing the "" with + Chr(34) + to no avail. What am I missing?
 
shabbs said:
I'm having a heck of a time trying to get this to work:

Regex.Replace(input, "(?<esc>['""\])", "\${esc}")

What I'd like is to take any ' (single-quote), " (double-quote) and \
(backslash) and prepend it with a backslash.

Does the above compile for you? It does not for me as the \] is a
regular expression escape for the closing square bracket and that way
the opening [ is not closed.

If I use
Console.WriteLine(Regex.Replace("a single quote ', a double
quote "", a backslash \", "(?<esc>['""\\])", "\${esc}"))

instead, where the backslash is escaped, then it works fine, the output is

a single quote \', a double quote \", a backslash \\

so any of those three characters is prepended with a backslash.
 
shabbs said:
I'm having a heck of a time trying to get this to work:
Regex.Replace(input, "(?<esc>['""\])", "\${esc}")
What I'd like is to take any ' (single-quote), " (double-quote) and \
(backslash) and prepend it with a backslash.

Does the above compile for you? It does not for me as the \] is a
regular expression escape for the closing square bracket and that way
the opening [ is not closed.

If I use
         Console.WriteLine(Regex.Replace("a single quote ', a double
quote "", a backslash \", "(?<esc>['""\\])", "\${esc}"))

instead, where the backslash is escaped, then it works fine, the output is

a single quote \', a double quote \", a backslash \\

so any of those three characters is prepended with a backslash.

Martin,

Thanks for the response. That is the way I had it, alas I failed to
copy it into the clipboard, so it should have worked. I found that my
problem was in fact that I was passing things in from the command line
for this particular test, and the command line (indeed from an actual
windows command prompt and from project options) did not parse the "
as part of the argument and therefore it was dropped. Once I escaped
the " on the *command line* properly, or if I sent a hard-coded string
through the function, everything worked as expected. Thanks again.

Csaba S.
 
Back
Top