2012-01-16 101 views

回答

3

我不認爲拆分字符串將是一種解決方案,因爲您需要知道拆分字符串的字符的位置。

所以,我給你兩個解決

解決方案#1

正則表達式

首先,你需要添加引用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 

解決方案#2

線性搜索

代碼

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

+1使用正則表達式,很好地完成。 – Jesse 2012-01-16 18:43:02

+1

+1,但建議您在執行前測試regexp,並在解決方案2中通過推測匹配 – brettdj 2012-01-17 03:52:28

+1

進行循環,那麼您最好使用instr函數,例如openbracepos = instr(startAt,stext,「{」)它比遍歷串起你自己 – ChrisPadgham 2012-01-18 00:45:36

相關問題