从单词列表中替换字符串中的多个单词 [英] Replace multiple words in a string from a list of words

查看:56
本文介绍了从单词列表中替换字符串中的多个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单词列表:

string [] BAD_WORDS = {"xxx","o2o"}//我的列表实际上比100个单词大得多

并且我有一些文本(通常很短,最多250个单词),我需要删除其中的所有 BAD_WORDS .

and i have some text (usually short , max 250 words), which i need to REMOVE all the BAD_WORDS in it.

我已经尝试过了:

    foreach (var word in BAD_WORDS)
    {
        string w = string.Format(" {0} ", word);
        if (input.Contains(w))
        {
            while (input.Contains(w))
            {
                input = input.Replace(w, " ");
            }
        }
    }

但是,如果文本以错误的词开头或结尾,则不会将其删除.我是用空格来做的,所以它不会与部分单词匹配,例如"oxxx"不应该删除,因为它与错误单词并不完全匹配.

but, if the text starts or ends with a bad word, it will not be removed. i did it with the spaces, so it will not match partial words for example "oxxx" should not be removed, since it is not an exact match to the BAD WORDS.

有人可以给我建议吗?

推荐答案

string cleaned = Regex.Replace(input, "\\b" + string.Join("\\b|\\b",BAD_WORDS) + "\\b", "")

这篇关于从单词列表中替换字符串中的多个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆