![](/img/trans.png)
[英]How can I enable a word-breaking function by length without split inside html-encoded special chars
[英]How to split special chars
所以我有一個代碼,我一直在努力讓它盡可能地發揮作用。 現在它工作得很好,雖然我需要它來過濾整個句子,不管任何特殊的字符纏繞在這個詞上。 例如,當我發送字符串時:
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;
}
如果我刪除特殊的字符,如!
從文字來看,它會起作用。 我可以很容易地將這些字符添加到char列表中,但肯定有一個非常簡單的方法嗎?
這可能會對你有所幫助因為它取決於你對特殊字符的定義。 我發現在大多數情況下,白名單而不是黑名單是最好的方法。
所以現在你留下了沒有特殊字符的字符串,你的代碼完成了剩下的部分。
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;
}
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);
我使用了兩個正則表達式,一個用於刪除任何不是字母字符的字符,另一個是用於刪除字符串中多余空格的正則表達式。 然后我將原始字符串設置為小寫以匹配禁止的單詞列表。 然后我簡單地將字符串拆分為空格。 希望這可以幫助。
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.