| | 1 | | using System.Collections.Generic; |
| | 2 | | using System.Text; |
| | 3 | | using System.Text.RegularExpressions; |
| | 4 | |
|
| | 5 | | public class RegexProfanityFilter |
| | 6 | | { |
| | 7 | | private readonly Regex regex; |
| | 8 | |
|
| 33 | 9 | | public RegexProfanityFilter(IProfanityWordProvider wordProvider) |
| | 10 | | { |
| 33 | 11 | | var explicitWords = ToRegex(wordProvider.GetExplicitWords()); |
| 33 | 12 | | var nonExplicitWords = ToRegex(wordProvider.GetNonExplicitWords()); |
| 33 | 13 | | regex = new Regex(@$"\b({explicitWords})\b|({nonExplicitWords})", RegexOptions.IgnoreCase); |
| 33 | 14 | | } |
| | 15 | |
|
| | 16 | | public string Filter(string message) |
| | 17 | | { |
| 114 | 18 | | if (string.IsNullOrEmpty(message)) return message; |
| 106 | 19 | | return regex.Replace(message, |
| 15 | 20 | | match => new StringBuilder().Append('*', match.Value.Length).ToString()); |
| | 21 | | } |
| | 22 | |
|
| 66 | 23 | | private string ToRegex(IEnumerable<string> words) => string.Join("|", words); |
| | 24 | | } |