我不相信Bittercode,因爲他說LINQ將超越正則表達式。 所以我做了一個小測試只是爲了確定。如何做到這一點
三個例子:
Dim _invalidChars As Char() = New Char() {"j"c, "a"c, "n"c}
Dim _textToStrip As String = "The quick brown fox jumps over the lazy dog"
Private Sub btnStripInvalidCharsLINQ_Click(sender As System.Object, e As System.EventArgs) Handles btnStripInvalidCharsLINQ.Click
Dim stripped As String = String.Empty
Dim sw As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To 10000
stripped = _textToStrip.Where(Function(c As Char) Not _invalidChars.Contains(c)).ToArray
Next
sw.Stop()
lblStripInvalidCharsLINQ.Text = _stripped & " - in " & sw.Elapsed.TotalMilliseconds & " ms"
End Sub
Private Sub btnStripInvalidCharsFOR_Click(sender As System.Object, e As System.EventArgs) Handles btnStripInvalidCharsFOR.Click
Dim stripped As String = String.Empty
Dim sw As Stopwatch = Stopwatch.StartNew
stripped = _textToStrip
For i As Integer = 0 To 10000
For Each c As Char In _invalidChars
stripped = stripped.Replace(c, "")
Next
Next
sw.Stop()
lblStipInvalidcharsFor.Text = stripped & " - in " & sw.Elapsed.TotalMilliseconds & " ms"
End Sub
Private Sub btnStripInvalidCharsREGEX_Click(sender As System.Object, e As System.EventArgs) Handles btnStripInvalidCharsREGEX.Click
Dim stripped As String = String.Empty
Dim sw As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To 10000
stripped = Regex.Replace(_textToStrip, "[" & New String(_invalidChars) & "]", String.Empty)
Next
sw.Stop()
lblStripInvalidCharsRegex.Text = stripped & " - in " & sw.Elapsed.TotalMilliseconds & " ms"
End Sub
結果:
所以,for循環與outperformes與string.replace所有其他方法。
因此,我會對字符串對象做一個擴展函數。
Module StringExtensions
<Extension()> _
Public Function ReplaceAll(ByVal InputValue As String, ByVal chars As Char(), replaceWith As Char) As String
Dim ret As String = String.Empty
For Each c As Char In chars
ret.Replace(c, replaceWith)
Next
Return ret
End Function
然後,你可以使用這個功能不錯,可讀取一行:
_textToStrip.ReplaceAll(_invalidChars, CChar(String.Empty))
來源
2012-11-21 07:55:13
JDC
這是一個「應該問精確問題而不是改寫它」的情況。詳細說來,我實際上有一個字符串,它基本上是一系列由空格分隔的單詞。我有一串我想從字符串中刪除的單詞,因此我認爲爲什麼我認爲每個foreach都可能/有用。當以這種方式詢問(不同的)問題時,正則表達式不適用。所以基本上: dim words()as string =(「the」,「brown」,「lazy」) dim sentence as string =「快速棕色狐狸跳躍」 results =「快速狐狸跳躍」 我的希望是words.ForEach(Function(w)sentence.Replace(w,「」) – hitch 2009-08-26 06:45:41