TG.WXCRM.V4/NetCore.Common/KeyWordHelper.cs

84 lines
3.0 KiB
C#

using System;
namespace NetCore.Common
{
/// <summary>
/// 关键词算法,有白名单算法
/// </summary>
public class KeyWordHelper
{
/// <summary>
/// 是否违规
/// </summary>
/// <param name="content"></param>
/// <param name="keyword"></param>
/// <returns></returns>
public static bool IsViolation(string content, string keyword)
{
bool result = false;
try
{
string newcontent = content.ToString();
string word = "";
string[] whitewords = { };
if (keyword.IndexOf("{") == -1)
{
word = keyword;
}
else
{
var xa = keyword.IndexOf("{");
word = keyword.Substring(0, xa);
whitewords = keyword.Substring(xa).Replace("{", "").Replace("}", "").Split(",");
}
if (content.Contains(word))
{
if (whitewords.Length == 0)//没有白名单直接返回true
{
return true;
}
int whitcount = 0;//白名单数量,要等于出现关键词的次数,才能算是全部在白名单中
int wordcount = 0;
while (newcontent.IndexOf(word) > -1)
{
wordcount++;
int i = newcontent.IndexOf(word);//关键词位置
bool needreplace = true;
foreach (var item in whitewords)
{
int mx = item.IndexOf(word);//关键词在白名单位置
if (mx == -1)
continue;//不在此白名单中
int worindex = newcontent.IndexOf(item);//白名单所在位置
if (worindex == i - mx)
{
needreplace = false;
whitcount++;
newcontent = newcontent.Substring(0, worindex) + newcontent.Substring(worindex + item.Length);//把白名单替换掉
break;
}
}
if (needreplace == true)
newcontent = newcontent.Substring(0, i) + newcontent.Substring(i + word.Length);//把白名单替换掉
}
if (whitcount == wordcount)
{
result = false;
}
else
{
result = true;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return result;
}
}
}