<%@ WebHandler Language="C#" Class="GwStrategyTestHandler" %>
|
|
using System;
|
using System.Web;
|
using System.Collections.Generic;
|
using System.Text.RegularExpressions;
|
|
public class GwStrategyTestHandler : IHttpHandler
|
{
|
public void ProcessRequest(HttpContext context)
|
{
|
string srcContent = ToString(context.Request["srcContent"]);
|
string wordList = ToString(context.Request["wordList"]);
|
|
IEnumerable<PatternStruct> patternList = ToWordExpressions(wordList);
|
|
PatternStruct pattern = null;
|
|
string resultMessage = "没有找到匹配内容";
|
|
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
|
|
sw.Start();
|
|
if (MatchContent(srcContent, patternList, ref pattern))
|
{
|
resultMessage = "匹配关键词:" + pattern.Src;
|
}
|
|
sw.Stop();
|
|
resultMessage += ";耗时" + sw.ElapsedTicks / 100 / 1000 + "ms";
|
|
context.Response.ContentType = "application/json";
|
context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new { OK = true, Message = resultMessage }));
|
}
|
|
public string ToString(string s)
|
{
|
if (s == null)
|
return string.Empty;
|
|
return s;
|
}
|
|
private static bool MatchContent(string srcContent, IEnumerable<PatternStruct> patternList, ref PatternStruct pattern)
|
{
|
foreach (var p in patternList)
|
{
|
if (Regex.IsMatch(srcContent, p.Pattern))
|
{
|
pattern = p;
|
return true;
|
}
|
}
|
|
return false;
|
}
|
|
class PatternStruct
|
{
|
public string Pattern { get;private set; }
|
public string Src { get;private set; }
|
|
public PatternStruct(string pattern, string src)
|
{
|
this.Pattern = pattern;
|
this.Src = src;
|
}
|
}
|
|
private IEnumerable<PatternStruct> ToWordExpressions(string source)
|
{
|
List<PatternStruct> list = new List<PatternStruct>();
|
|
string[] lineArray = source.Split(";,;,\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
|
|
foreach (string line in lineArray)
|
{
|
string temp = line;
|
temp = temp.Replace(@"\", @"\\");
|
temp = temp.Replace(@"|", @"\|");
|
temp = temp.Replace(@"^", @"\^");
|
temp = temp.Replace(@"$", @"\$");
|
temp = temp.Replace(@"{", @"\{");
|
temp = temp.Replace(@"}", @"\}");
|
temp = temp.Replace(@"(", @"\(");
|
temp = temp.Replace(@")", @"\)");
|
temp = temp.Replace(@"[", @"\[");
|
temp = temp.Replace(@"]", @"\]");
|
temp = temp.Replace(@":", @"\:");
|
temp = temp.Replace(@".", @"\.");
|
temp = temp.Replace(@"?", @"\?");
|
temp = temp.Replace(@"-", @"\-");
|
temp = temp.Replace(@",", @"\,");
|
|
string pattern = Regex.Replace(temp, @"(\*+)", delegate(Match m) { return @"[\w\W]{0," + (m.Groups[1].Value.Length * 10) + "}?"; });
|
|
list.Add(new PatternStruct(pattern,line));
|
}
|
|
return list;
|
}
|
|
|
public bool IsReusable
|
{
|
get
|
{
|
return false;
|
}
|
}
|
|
}
|