Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape special characters in regex?

Tags:

c#

regex

This code searches a richtextbox and replaces the first field of the array into the second one. It all works fine except for two of the fields.

iEmo = new string[,] {
  {@":\)",    Smile},
  {@":\(",    Sad},
  {@"8\)",    Cool},
  {@":\|",    Neutral},
  {@";\)",    Wink},
  {@">:\(",   Evil},    // Won't work for this one
  {@">:D",    Twisted}, // Or this one
  {@":\?",    Question,}
};

Here's the part that converts the array into what I want:

public void SetSmiley(RichTextBox RichBox) {
  for (int i = 0; i < (iEmo.Length / 3); i++) {
    try {
      RichBox.Rtf = Regex.Replace(RichBox.Rtf, iEmo[i, 0], iEmo[i, 1], RegexOptions.IgnoreCase);
    }
    catch (Exception e){}
  }
}
like image 455
user1667191 Avatar asked Nov 18 '12 02:11

user1667191


1 Answers

Your regular expression looks fine, though I see a few things that are preventing it from working:

for (int i = 0; i < (iEmo.Length / 3); i++)

I have no idea why you're dividing by 3. You should use the first dimension's length here instead:

for (int i = 0; i < iEmo.GetLength(0); i++)

Additionally, because of the order in which your replacements occur, the normal frown ":(" will be replaced before the "evil" face ">:(". By the time the loop gets to the evil case, the string looks like ">Sad". Your should rearrange your replacements in descending complexity, something like this:

iEmo = new string[,]
{
    {@">:\(",   Evil},
    {@":\)",    Smile},
    {@":\(",    Sad},
    {@"8\)",    Cool},
    {@":\|",    Neutral},
    {@";\)",    Wink},
    {@">:D",    Twisted},
    {@":\?",    Question,}
};

And again, normal string replacement will work fine with the above changes.

like image 142
Patrick Quirk Avatar answered Oct 06 '22 21:10

Patrick Quirk