所以我有一个代码,我一直在努力让它尽可能地发挥作用。现在它工作得很好,虽然我需要它来过滤整个句子,不管任何特殊的字符缠绕在这个词上。例如,当我发送字符串时:
JOIN GooGle | × ,,. ¬ hiring !HOteL, it is ++ !!free!! ,, ..!community;;+_
被禁止的单词join, hiring, hotel, free, community
它不会检测到上面的句子。
我的代码是:
public bool CheckSentence(string messageText.ToLower())
{
var count = 0;
string[] wordsInMessage = messageText.Split(new char[] { ' ', ',' },
StringSplitOptions.RemoveEmptyEntries);
foreach (WordFilter Filter in this._filteredWords.ToList())
{
count += wordsInMessage.Count(x => x == Filter.Word);
}
return count >= 3;
}
如果我从单词中删除!
之类的特殊字符,它将起作用。我可以很容易地将这些字符添加到字符列表中,但肯定有一个非常简单的方法吗?
答案 0 :(得分:4)
这可能会对你有所帮助因为它取决于你对特殊字符的定义。我发现在大多数情况下,白名单而不是黑名单是最好的方法。
所以现在你留下了没有特殊字符的字符串,你的代码完成了剩下的部分。
public bool CheckSentence(string messageText.ToLower())
{
messageText = Regex.Replace(messageText, @"[^a-z0-9 ]", "");
var count = 0;
string[] wordsInMessage = messageText.Split(new char[] { ' ', ',' },
StringSplitOptions.RemoveEmptyEntries);
foreach (WordFilter Filter in this._filteredWords.ToList())
{
count += wordsInMessage.Count(x => x == Filter.Word);
}
return count >= 3;
}
答案 1 :(得分:0)
string testData = @"JOIN GooGle | × ,,. ¬ hiring !HOteL, it is ++!!free!! ,, ..!community; ; +_";
List<string> bannedWords = new List<string>
{
"join",
"hiring",
"hotel",
"free",
"community"
};
bannedWords.ForEach(word =>
{
int startIndex = testData.IndexOf(word, StringComparison.InvariantCultureIgnoreCase);
if(startIndex == -1) return;
testData = testData.Remove(startIndex, word.Length);
});
Console.WriteLine(testData);
答案 2 :(得分:0)
我使用了两个正则表达式,一个用于删除任何非字母字符的字符,另一个用于删除字符串中多余空格的正则表达式。然后我将原始字符串设置为小写以匹配禁止的单词列表。然后我简单地将字符串拆分为空格。希望这会有所帮助。
static String input = "JOIN GooGle | × ,,. ¬ hiring !HOteL, it is ++ !!free!! ,, ..!community;;+_";
static Regex charOnly = new Regex("[^a-zA-Z ]");
static Regex extarSpaces = new Regex(@"\s{2,}");
static List<String> bannedWords = new List<String> { "join", "hiring", "hotel", "free", "community" };
static void Main(string[] args) {
string originalString = charOnly.Replace(input, "");
originalString = extarSpaces.Replace(originalString, " ");
originalString = originalString.ToLower();
string[] splitArray = originalString.Split(' ');
int count = 0;
for (int i = 0; i < splitArray.Length; i++) {
if (splitArray[i] != null) {
if (bannedWords.Contains(splitArray[i].ToString())) {
count++;
Console.WriteLine("Banned: " + splitArray[i].ToString());
}
}
}
Console.WriteLine("originalString: " + originalString);
Console.WriteLine("splitArray Size: " + splitArray.Length);
Console.WriteLine("Banned Words in string = " + count);
Console.ReadKey();
}