1
我需要一個字符串中兩個字符之間的值。值在{和}之間。有時可能會有更多的發生。在字符串中的兩個字符之間得到值
var = split("this {is} a {test}","{")
var = split("this {is} a {test}","}")
我需要一個字符串中兩個字符之間的值。值在{和}之間。有時可能會有更多的發生。在字符串中的兩個字符之間得到值
var = split("this {is} a {test}","{")
var = split("this {is} a {test}","}")
我不認爲拆分字符串將是一種解決方案,因爲您需要知道拆分字符串的字符的位置。
所以,我給你兩個解決
首先,你需要添加引用VBA正則表達式。 Tool -> References & Microsoft VBScript Regular Expression 5.5
Sub Test1()
Dim sText As String
Dim oRegExp As RegExp
Dim oMatches As MatchCollection
sText = "this {is} a {test}"
Set oRegExp = New RegExp
With oRegExp
oRegExp.IgnoreCase = True
oRegExp.Pattern = "{([^\}]+)"
oRegExp.Global = True
End With
Set oMatches = oRegExp.Execute(sText)
For Each Text In oMatches
Debug.Print Mid(Text, 2, Len(Text))
Next
End Sub
Sub Test2()
Dim bIsBetween As Boolean
Dim iLength As Integer
Dim sText As String
Dim sToken As String
bIsBetween = False
sToken = ""
sText = "this {is} a {test}"
iLength = Len(sText) - 1
For I = 1 To iLength
Dim chr As String
Dim nextChr As String
chr = Mid(sText, I, 1)
nextChr = Mid(sText, I + 1, 1)
If (chr = "{") Then
bIsBetween = True
End If
If (nextChr = "}") Then
bIsBetween = False
End If
If (bIsBetween = True) Then
sToken = sToken & nextChr
Else
If (Len(sToken) > 0) Then
Debug.Print sToken
sToken = ""
End If
End If
Next I
End Sub
+1使用正則表達式,很好地完成。 – Jesse 2012-01-16 18:43:02
+1,但建議您在執行前測試regexp,並在解決方案2中通過推測匹配 – brettdj 2012-01-17 03:52:28
進行循環,那麼您最好使用instr函數,例如openbracepos = instr(startAt,stext,「{」)它比遍歷串起你自己 – ChrisPadgham 2012-01-18 00:45:36