代码之家  ›  专栏  ›  技术社区  ›  zgorawski

如何从字符串中剪切指定单词

  •  5
  • zgorawski  · 技术社区  · 14 年前

    这里有一个禁止使用的单词列表(或者更一般的字符串)和另一个包含用户邮件的列表。我想删除所有邮件中的所有禁止词。

    简单的例子:

    foreach(string word in wordsList)
    {
       foreach(string mail in mailList)
       {
          mail.Replace(word,String.Empty);
       }
    }
    

    如何改进这个算法?


    谢谢你的建议。我对答案投了很少的票,但我没有把任何答案作为答案,因为它更像是讨论而不是解决方案。有些人用脏话漏掉了违禁词。在我的例子中,我不必费心去识别“sh1t”或类似的东西。

    12 回复  |  直到 12 年前
        1
  •  2
  •   Justin Niessner    14 年前

    var bannedWords = @"\b(this|is|the|list|of|banned|words)\b";
    
    foreach(mail in mailList)
        var clean = Regex.Replace(mail, bannedWords, "", RegexOptions.IgnoreCase);
    

        4
  •  1
  •   Heinzi    14 年前

    word1|word2|word3|... \b(word1|word2|word3|...)\b

        5
  •  1
  •   Michael Petito    14 年前

    Replace Regex

    HashSet<string> BannedWords = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase)
    {
        "bad",
    };
    
    string Input = "this is some bad text.";
    
    string Output = Regex.Replace(Input, @"\b\w+\b", (Match m) => BannedWords.Contains(m.Value) ? new string('x', m.Value.Length) : m.Value);
    
        6
  •  1
  •   Jon Hanna    14 年前

    * Grand ******* of Normandy"

        7
  •  1
  •   Saeed Amiri    14 年前

        8
  •  0
  •   Andrew Barber Eric Lafortune    14 年前

    Regex

    "\bBADWORD\b"
    

        9
  •  0
  •   T.E.D.    14 年前

    *

        10
  •  0
  •   Turner Hayes    14 年前

        11
  •  0
  •   Dialecticus    14 年前

        12
  •  0
  •   kenny    14 年前