使用 Replace 函式 (Visual Basic),Expression 的長度為零或 Nothing,或 Start 大於 Expression 的長度,回傳值就是會是 Nothing 哦!
今天跟同事在查一個「System.NullReferenceException: 並未將物件參考設定為物件的執行個體」的錯誤!
後來發現字串經過 Replace Function 處理過後就回傳 Nothing 。
所以就使用以下的 VB.NET Console 的程式來測試,如下,
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim exp As String = String.Empty
Dim result As String = String.Empty
'一般字串測試
exp = "123Find"
result = VBReplaceTest(exp)
Console.WriteLine(String.Format("VB Replace, 123Find->find->replace:[{0}]", result))
result = StringReplaceTest(exp)
Console.WriteLine(String.Format("String.Replace, 123Find->find->replace:[{0}]", result))
result = RegexReplaceTest(exp)
Console.WriteLine(String.Format("Regex.Replace, 123Find->find->replace:[{0}]", result))
'空白字串測試
exp = " "
result = VBReplaceTest(exp)
Console.WriteLine(String.Format("VB Replace, [ ]->find->replace:[{0}]", result))
result = StringReplaceTest(exp)
Console.WriteLine(String.Format("String.Replace, [ ]->find->replace:[{0}]", result))
result = RegexReplaceTest(exp)
Console.WriteLine(String.Format("Regex.Replace, [ ]->find->replace:[{0}]", result))
'空字串測試
exp = String.Empty
result = VBReplaceTest(exp)
Console.WriteLine(String.Format("VB Replace, string.empty->find->replace:[{0}]", _
IIf(IsNothing(result), "Nothing", result)))
result = StringReplaceTest(exp)
Console.WriteLine(String.Format("String.Replace, string.empty->find->replace:[{0}]", _
IIf(IsNothing(result), "Nothing", result)))
result = RegexReplaceTest(exp)
Console.WriteLine(String.Format("Regex.Replace, string.empty->find->replace:[{0}]", _
IIf(IsNothing(result), "Nothing", result)))
Console.ReadLine
End Sub
Const finder As String = "find"
Const replacement As String = "replace"
Function VBReplaceTest(ByVal exp As String) As String
Dim result As String = String.Empty
result = Replace(exp, finder, replacement, 1, -1, CompareMethod.Text)
Return result
End Function
Function StringReplaceTest(ByVal exp As String) As String
Dim result As String = String.Empty
result = exp.Replace(finder, replacement)
Return result
End Function
Function RegexReplaceTest(ByVal exp As String) As String
Dim r As Regex = New Regex(finder, RegexOptions.IgnoreCase)
Dim result As String = String.Empty
result = r.Replace(exp, replacement)
Return result
End Function
End Module
測試結果如下,
使用 Replace 函式 (Visual Basic),Expression 的長度為零或 Nothing,或 Start 大於 Expression 的長度,回傳值就是會是 Nothing 哦!
另外,如果使用 String.Replace 方法 (String, String) 的話(StringReplaceTest),字串大小寫就無法 replace 到!
所以,如果要處理不分大小寫的話,可以使用 Regex.Replace 方法 (String, String) ,如Demo程式的 RegexReplaceTest 所示。!
參考資料
String.Replace 方法 (String, String)
Regex.Replace 方法 (String, String)
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^