如何逃避正则表达式中的特殊字符?

时间:2022-10-16 22:24:54

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.

此代码搜索richtextbox并将数组的第一个字段替换为第二个字段。除了两个字段外,一切正常。

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){}
  }
}

1 个解决方案

#1


5  

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:

我不知道你为什么要除以3.你应该在这里使用第一个维度的长度:

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.

再次,正常的字符串替换将适用于上述更改。

#1


5  

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:

我不知道你为什么要除以3.你应该在这里使用第一个维度的长度:

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.

再次,正常的字符串替换将适用于上述更改。