我想提取用括号括起来的值。
text = "那个 {said} 和 {var2} 以及 {var3} 的人
openingParen = InStr(text, "{")
closingParen = InStr(text, "}")
enclosedValue = Mid(text, openingParen + 1, closingParen - openingParen - 1)
phrasevariable1.Value = enclosedValue
phrasevariable2.Value = enclosedValue
phrasevariable3.Value = enclosedValue
此代码仅适用于提取第一个值,有没有办法提取每个变量,并相应地将它们放入文本框 1 -> n
您可以将正则表达式用于未知数量的候选令牌;
Dim matches As Object
Dim Re As Object: Set Re = CreateObject("vbscript.regexp")
Dim count As Long
Re.Pattern = "{(.*?)}"
Re.Global = True
Set matches = Re.Execute("The man who {said} and also {var2} as well as {var3}")
count = matches.count
For i = 0 To count - 1
MsgBox matches(i).submatches(0)
Next
(添加引用以Microsoft VBScript 正则表达式以进行早期绑定)
允许任意数量的匹配的另一种方式:
Const stri As String = "The man who {said} and also {var2} as well as {var3}"
Dim sp
sp = Filter(Split(Replace(Chr(13) & stri, "}", "{" & Chr(13)), "{"), Chr(13), False)
假设括号中始终有三对文本,只需创建一个数组变量,并在文本字符串上使用split
来获取值:
Dim myArray
myArray = Split(text, "{")
phasevariable1.Value = Left(myArray(1), InStr(myArray(1), "}") - 1)
phasevariable2.Value = Left(myArray(2), InStr(myArray(2), "}") - 1)
phasevariable3.Value = Left(myArray(3), InStr(myArray(3), "}") - 1)