我在ASP Classic / VBScript中有以下字符串:
Y157019=1&Y013759=2&Y032231=5
我想将字符串修改为:
Update TABLEX SET Status='1' WHERE Ticket= 'Y157019'; Update TABLEX SET Status='2' WHERE Ticket= 'Y013759'; Update TABLEX SET Status='5' WHERE Ticket= 'Y032231';
我尝试使用Replace()
但无法使其正常工作,因为字符串中的值位于名称之后。
答案 0 :(得分:4)
您可以Split()
将您的字符串转换为key=value
对数组,然后进一步Split()
这些对,以便单独提取关键字和值。
例如:
Const FIELDS = "Y157019=1&Y013759=2&Y032231=5"
a = Split(FIELDS, "&")
s = ""
For Each kv In a
If InStr(kv, "=") > 0 Then
k = Split(kv, "=")(0)
v = Split(kv, "=")(1)
s = s & "Update TABLEX SET Status='" & v & "' WHERE Ticket= '" & k & "'; "
End If
Next
WScript.Echo s
答案 1 :(得分:2)
使用RegExp将输入(sInp)拆分为键值部分,然后将这些部分替换为从所需输出(sExp)派生的模板(sTmpl):
Option Explicit
' 1 2 3 4 5 6
Dim sInp : sInp = "Y157019=1&Y013759=2&Y032231=5"
Dim sExp : sExp = "Update TABLEX SET Status='1' WHERE Ticket= 'Y157019'; Update TABLEX SET Status='2' WHERE Ticket= 'Y013759'; Update TABLEX SET Status='5' WHERE Ticket= 'Y032231';"
Dim sTmpl : sTmpl = Join(Array( _
"Update TABLEX SET Status='$2' WHERE Ticket= '$1'" _
, "Update TABLEX SET Status='$4' WHERE Ticket= '$3'" _
, "Update TABLEX SET Status='$6' WHERE Ticket= '$5';" _
), "; ")
Dim reRpl : Set reRpl = New RegExp
reRpl.Pattern = "^([^=]+)=(\d+)&([^=]+)=(\d+)&([^=]+)=(\d+)$"
Dim sAct : sAct = reRpl.Replace(sInp, sTmpl)
WScript.Echo sExp
WScript.Echo sAct
WScript.Echo CStr(sAct = sExp)
输出:
cscript 31453580.vbs Update TABLEX SET Status='1' WHERE Ticket= 'Y157019'; Update TABLEX SET Status='2' WHERE Ticket= 'Y013759'; Update TABLEX SET Status='5' WHERE Ticket= 'Y032231'; Update TABLEX SET Status='1' WHERE Ticket= 'Y157019'; Update TABLEX SET Status='2' WHERE Ticket= 'Y013759'; Update TABLEX SET Status='5' WHERE Ticket= 'Y032231'; True
适应更改后的规范:
Option Explicit
Dim aTests : aTests = Array( _
"Y157019=1&Y013759=2&Y032231=5" _
, "Y157019=1&Y013759=2" _
, "Y157019=1" _
, "" _
)
Dim reRpl : Set reRpl = New RegExp
reRpl.Global = True
reRpl.Pattern = "([^=]+)=(\d+)"
Dim sInp
For Each sInp In aTests
WScript.Echo "----", sInp
Dim oMts : Set oMts = reRpl.Execute(sInp)
Dim sAct
If 0 < oMts.Count Then
ReDim aTmp(oMTS.Count - 1)
Dim i
For i = 0 To UBound(aTmp)
aTmp(i) = reRpl.Replace(oMTS(i).Value, "Update TABLEX SET Status='$2' WHERE Ticket= '$1'")
Next
sAct = Join(aTmp, "; ") & ";"
Else
sAct = "no match"
End If
WScript.Echo sAct
Next
输出:
cscript 31453580-2.vbs ---- Y157019=1&Y013759=2&Y032231=5 Update TABLEX SET Status='1' WHERE Ticket= 'Y157019'; Update TABLEX SET Status='2' WHERE Ticket= '&Y013759'; Update TABLEX SET Status='5' WHERE Ticket= '&Y032231'; ---- Y157019=1&Y013759=2 Update TABLEX SET Status='1' WHERE Ticket= 'Y157019'; Update TABLEX SET Status='2' WHERE Ticket= '&Y013759'; ---- Y157019=1 Update TABLEX SET Status='1' WHERE Ticket= 'Y157019'; ---- no match