String.Replace and Regex.Replace not working with special characters inside IComparer

1.5k views Asked by At

The following console app works fine:

class Program
{
    static void Main(string[] args)
    {
        string plainx = "‘test data’ random suffix";
        plainx = Regex.Replace(plainx, @"‘", string.Empty);
        Console.WriteLine(plainx);
    }
}

However its giving me trouble in an ASP.Net application.. I am attaching a screenshot of the VS Debug watch window and Immediate window

(Click for larger view)
enter image description here

As you can see, the Regex.Replace in the Immediate Window works - but somehow it is not working in the code (line 71). I've also used String.Replace without success.

Edit It seems the value that was stored in the DB is something than what the editor shows... kind of weird.. enter image description here

3

There are 3 answers

0
Scott Chamberlain On BEST ANSWER

The single quote in your code is not the same single quote in the string you are testing.

Use the hex value returned from testx[0] directly to guarantee that we are using the correct quote.

plainx = Regex.Replace(plainx, "\u2018", string.Empty);
1
Nicholas Carey On

Have you actually examined the text being compared? What Unicode code points does it contain?

Your code shows you trying to replace the glyph '‘', which is a left "smart quote". The character's name is LEFT SINGLE QUOTATION MARK and its code point is 0x2018 (aka '\u2018'). This is a character you can't ordinarily enter on a keyboard.

What you are probably seeing is the glyph '`', a "backtick". Its character name is GRAVE ACCENT and its code point is 0x0060 (aka '\u0060'). This is the character typed when you press the [unshifted] tilde key on a standard US keyboard (leftmost key on the number row).

It might, of course, be any of a number of other characters whose glyph is similar to a single quote. See Commonly Confused Characters for more information.

0
penjepitkertasku On

try to replace :

@"‘" to @"\‘"

code :

string plainx = "‘test data’ random suffix";
plainx = System.Text.RegularExpressions.Regex.Replace(plainx, @"\‘", string.Empty);
Console.WriteLine(plainx);
Console.Read();