【发布时间】:2017-12-04 08:46:13
【问题描述】:
我有一个坏词替换 VB.net 的脚本,这导致了很多问题。经过多次试验和错误,当前代码可以工作,但不会过滤掉有大写字母的单词。
Private Function CheckForBadWords(ByVal InputString As String) As String
Dim r As Regex
Dim element As String
Dim eLength As Integer
Dim x As Integer
Dim AttachtoEnd As String
For Each element In alWordList
r = New Regex("\b" & element)
eLength = element.Length
For x = 3 To eLength - 1
AttachtoEnd = AttachtoEnd & "*"
Next
InputString = r.Replace(InputString, element, Left(element, 3) & AttachtoEnd)
AttachtoEnd = ""
Next
Return InputString
End Function
如何让它检查带有大写字母的单词?例如:phuck 将得到检查,因为 Phuck 或 PHUCK 不会得到检查。
我尝试按照本教程进行操作,但它是用 C# 编写的,而且我几乎不知道 VB.net: http://www.dreamincode.net/forums/topic/67129-creating-a-bad-word-filter-functionality-in-aspnet-wc%23/
添加更多细节:在一些帮助下,这似乎在多次调整后有效,但错误仍然存在,特别是引号和双引号或
s。
Private Function CheckForBadWords(ByVal InputString As String) As String
Dim starPosition As Integer = 0
Dim element As String
Dim eLength As Integer
Dim x As Integer
Dim AttachtoEnd As String
Dim strArray = InputString.Split(" ")
Dim specialChars As New List(Of String)(New String() {"@", "!", ".", ",", "(", ")", "/", "#", "$", "&", "+", "-", "_", "=", ":", "'", "*", "^", "`", "<", ">", "[", "]", "{", "}", "\", "|", ControlChars.Quote})
Dim firstChars As String = ""
Dim LastChars As String = ""
InputString = String.Empty
For Each item As String In strArray
Dim str As String = item
firstChars = String.Empty
LastChars = String.Empty
For Each ch As Char In str
If Not specialChars.Contains(ch) Then
Exit For
Else
firstChars += ch
End If
Next
For Each spChar As Char In firstChars.ToCharArray()
str = str.Trim(spChar)
Next
For i As Integer = str.Length - 1 To 0 Step -1
If Not specialChars.Contains(str(i)) Then
Exit For
Else
LastChars = str(i) + LastChars
End If
Next
For Each spChar As String In specialChars
str = str.Trim(spChar)
Next
If Not String.IsNullOrWhiteSpace(str) Then
For Each element In alWordList
If element.ToLower = str.ToLower Then
str = str.Trim()
eLength = element.Length
For x = 3 To eLength - 1
AttachtoEnd = AttachtoEnd & "*"
starPosition += 1
Next
str = str.Substring(0, str.Length - starPosition) & AttachtoEnd
End If
AttachtoEnd = ""
starPosition = 0
Next
End If
InputString += firstChars + str + LastChars & " "
Next
Return InputString
End Function
所以现在我认为最好回到正则表达式,它的效果非常好,只需要它也能处理大写字母。
最后一点...要检查的单词以数组列表的形式出现。
【问题讨论】:
-
把所有的坏词变成小写。然后将您要检查的字符串转换为小写。然后进行检查。
-
您只想替换单词,或者如果“坏词”是
phuckcheck之类的子字符串? -
当前代码适用于整个字符串。但是当“坏”词中有任何类型的大写字母时,它就不能正常工作。请在答案中提供一些示例代码。
标签: vb.net