我有一個字串形式的 SQL 語法,其中有一些以標準方式撰寫的引數“,”。然后我有另一個字串,引數值也以標準方式撰寫:“Parameter1=123;Parameter2=aaa”。我需要將第一個 SQL 中的引數與第二個 SQL 中的值進行匹配。
到目前為止我所擁有的:`
Dim BodySQL = "Blablabal WHERE X=<Parameter1> AND Y=<Parameter2>"
Dim vmp As RegularExpressions.MatchCollection = RegularExpressions.Regex.Matches("Parameter1=2555; Parameter2 = 12/02/2021", "([\w ] )=([\w ] )")
Dim vmc As RegularExpressions.MatchCollection = RegularExpressions.Regex.Matches(BodySQL, "(?<=\<). ?(?=\>)")
For Each vm As RegularExpressions.Match In vmc
Dim Vl As String = (From m As RegularExpressions.Match In vmp
Where m.Groups(1).Value.Trim = vm.Value.ToString).Select(Of String)(Function(f) f.Groups(2).Value).ElementAt(0).Trim
BodySQL = BodySQL.Replace(vm.Value, Vl)
Next
` 它適用于第一個引數,但隨后我得到“System.ArgumentOutOfRangeException:'指定的引數超出了有效值的范圍。引數名稱:索引'”
請問為什么?
uj5u.com熱心網友回復:
您可以使用一個正則運算式從param=value字串中提取鍵和值,從中創建一個字典,然后使用Regex.Replace字典值替換匹配項:
Imports System.Text.RegularExpressions
' ...
Dim BodySQL = "Blablabal WHERE X=<Parameter1> AND Y=<Parameter2>"
Dim args As New Dictionary(Of String, String)(StringComparer.InvariantCultureIgnoreCase)
' (StringComparer.InvariantCultureIgnoreCase) makes the dictionary keys case insensitive
For Each match As Match In Regex.Matches("PARAMETER1=2555; Parameter2 = 12/02/2021", "(\S )\s*=\s*([^;]*[^;\s])")
args.Add(match.Groups(1).Value, match.Groups(2).Value)
Next
Console.WriteLine(Regex.Replace(BodySQL, "<([^<>]*)>",
Function(match)
Return If(args.ContainsKey(match.Groups(1).Value), args(match.Groups(1).Value), match.Value)
End Function))
輸出:
Blablabal WHERE X=2555 AND Y=12/02/2021
該(\S )\s*=\s*([^;]*[^;\s])模式匹配
(\S )- 將任何一個或多個非空白字符(鍵值)捕獲到組 1 中\s*=\s*- 一個=用零個或多個空格字符括起來的字符([^;]*[^;\s])- 第 2 組:;除;和空格以外的任何零個或多個字符(該值,此模式不能為空。如果您希望它可以匹配空值,則需要洗掉[^;\s]然后使用Trim()的match.Groups(2).Value代碼。)
在<([^<>]*)>正則運算式匹配
<- 一個<字符(請不要以任何正則運算式的形式轉義這個字符,它從來都不是一個特殊的正則運算式元字符)([^<>]*)- 第 1 組:除<和之外的任何零個或多個字符>>- 文字>字符。
由于密鑰在第 1 組中,<并且>兩端都消耗了<和 ,>因此在替換為找到的值時將洗掉和。零或比其它更多字符>和<之間<和>。
uj5u.com熱心網友回復:
該錯誤是不言自明的。您正在嘗試訪問陣列或串列并指定一個負數或大于可用最大索引的索引值。
.ElementAt(0) / m.Groups(1) / f.Groups(2)
我的猜測是其中一個可能會越界。嘗試使用斷點除錯它并檢查變數的值。
uj5u.com熱心網友回復:
這是我對你的代碼所做的:
Dim vmc = "\<(.*?)\>"
我改變了這個正則運算式,這樣它也可以給我“<>”
Dim BodySQL = "Blablabal WHERE X=<Parameter1> AND Y=<Parameter2>"
Dim args As New Dictionary(Of String, String)
For Each match As Match In Regex.Matches("Parameter1=2555; Parameter2 = 12/02/2021", "(\S )\s*=\s*(\S[^;] )")
我更改了正則運算式以排除“;”
args.Add(match.Groups(1).Value, match.Groups(2).Value)
Next
Console.WriteLine(Regex.Replace(BodySQL, vmc,
Function(match As Match)
Return If(args.ContainsKey(match.Groups(1).Value), args(match.Groups(1).Value), match.Value)
End Function))
現在我有了我需要的東西。非常感謝 :)
輸出:
WHERE X = 2555,Y = 12/02/2021
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/378913.html
上一篇:請幫我修復它。我需要一種方法,我必須使用else按下一個按鈕,將我移動到另一種形式
下一篇:SQLite引數超出范圍
