1

我想提取括号括起来的值。

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

4

3 回答 3

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 正则表达式添加一个引用以进行早期绑定)

于 2012-10-10T15:40:42.720 回答
3

另一种允许任意数量匹配的方法:

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)
于 2012-10-10T15:45:11.527 回答
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)
于 2012-10-10T15:32:21.867 回答