Mike Flynn
Mike Flynn

Reputation: 24325

C# Regex To Escape Certain Characters

How can I escape certain characters in a string with a C# Regex?

This is a test for % and ' thing? -> This is a test for \% and \' thing?

Upvotes: 3

Views: 1592

Answers (3)

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

resultString = Regex.Replace(subjectString, 
    @"(?<!      # Match a position before which there is no
     (?<!\\)    # odd number of backlashes
     \\         # (it's odd if there is one backslash,
     (?:\\\\)*  # followed by an even number of backslashes)
    )
    (?=[%'])    # and which is followed by a % or a '", 
    @"\", RegexOptions.IgnorePatternWhitespace);

However, if you're trying to protect yourself against malevolent SQL queries, regex is not the right way to go.

Upvotes: 2

Saeed Amiri
Saeed Amiri

Reputation: 22555

I don't think this could be done with regex in good fashion, but you can simply run a for loop:

var specialChars = new char[]{'%',....};
var stream = "";
for (int i=0;i<myStr.Length;i++)
{
   if (specialChars.Contains(myStr[i])
   {
       stream+= '\\'; 
   }
   stream += myStr[i];
}

(1) you can use StringBuilder to prevent from too many string creation.

Upvotes: 0

KeithS
KeithS

Reputation: 71563

var escapedString = Regex.Replace(input, @"[%']", @"\$1");

This is pretty much all you need. Inside the square brackets, you should put every character you wish to escape with a backslash, which may include the backslash character itself.

Upvotes: 1

Related Questions