using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
/// <summary>
/// Summary description for BadWordFilter
/// </summary>
public class BadWordFilter
{
/// <summary>
/// Private constructor and instantiate the list of regex
/// </summary>
private BadWordFilter()
{
//
// TODO: Add constructor logic here
//
Patterns = new List<Regex>();
}
/// <summary>
/// The patterns
/// </summary>
static List<Regex> Patterns;
private static BadWordFilter m_instance = null;
public static BadWordFilter Instance
{
get
{
if (m_instance == null)
m_instance = CreateBadWordFilter("listofwords.xml");
return m_instance;
}
}
/// <summary>
/// Create all the patterns required and add them to the list
/// </summary>
/// <param name="badWordFile"></param>
/// <returns></returns>
protected static BadWordFilter CreateBadWordFilter(string badWordFile)
{
BadWordFilter filter = new BadWordFilter();
XmlDocument badWordDoc = new XmlDocument();
badWordDoc.Load(badWordFile);
//Loop through the xml document for each bad word in the list
for (int i = 0; i < badWordDoc.GetElementsByTagName("word").Count; i++)
{
//Split each word into a character array
char[] characters = badWordDoc.GetElementsByTagName("word")[i].InnerText.ToCharArray();
//We need a fast way of appending to an exisiting string
StringBuilder patternBuilder = new StringBuilder();
//The start of the patterm
patternBuilder.Append("(");
//We next go through each letter and append the part of the pattern.
//It is this stage which generates the upper and lower case variations
for (int j = 0; j < characters.Length; j++)
{
patternBuilder.AppendFormat("[{0}|{1}][\\W]*", characters[j].ToString().ToLower(), characters[j].ToString().ToUpper());
}
//End the pattern
patternBuilder.Append(")");
//Add the new pattern to our list.
Patterns.Add(new Regex(patternBuilder.ToString()));
}
return filter;
}
/// <summary>
/// The function which returns the manipulated string
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public string GetCleanString(string input)
{
for (int i = 0; i < Patterns.Count; i++)
{
//In this instance we actually replace each instance of any bad word with a specified string.
input = Patterns[i].Replace(input, "####");
}
//return the manipulated string
return input;
}
public bool IsCleanString(string input)
{
for (int i = 0; i < Patterns.Count; i++)
{
//In this instance we actually replace each instance of any bad word with a specified string.
if (Patterns[i].IsMatch(input))
{
return false;
}
}
//return the manipulated string
return true;
}
}
|