我想提取括号括起来的值。
text =“{say}和{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 - >因此
答案 0 :(得分:5)
您可以将正则表达式用于未知数量的候选令牌;
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正则表达式添加引用以进行早期绑定)
答案 1 :(得分:1)
假设您在括号中总是有三对文本,只需创建一个数组变量,并在文本字符串上使用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)
答案 2 :(得分:1)
允许任意数量匹配的另一种方式:
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)