Regular expression involving double-quotes

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?
 
M

Martin Honnen

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.
 
S

shabbs

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top