Extracting Text Between Brackets with Regex

后端 未结 4 1351
情书的邮戳
情书的邮戳 2021-01-19 12:24

In sentences like:

\"[x] Alpha

[33] Beta\"

I extract an array of bracketed data as ([x], [33])

using VBA regex Pattern:

\"(\\         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-19 13:04

    Try this:

    \[(x)\]|\[(\d*)\]
    

    What you don't want to be captured, don't put them inside (). this is used for grouping

    Explanation

    You will get x and 33 in $1 and $2
    

    Dot Net Sample

    Alright, I prepared it for you , although far away from vb for long. Lots of it might be not needed, yet it might help you to understand it better

    Imports System.Text.RegularExpressions
    
    Module Example
       Public Sub Main()
          Dim text As String = "[x] Alpha      [33] Beta]"
          Dim pattern As String = "\[(x)\]|\[(\d*)\]"
    
          ' Instantiate the regular expression object.
          Dim r As Regex = new Regex(pattern, RegexOptions.IgnoreCase)
    
          ' Match the regular expression pattern against a text string.
          Dim m As Match = r.Match(text)
          Dim matchcount as Integer = 0
          Do While m.Success
             matchCount += 1
             Console.WriteLine("Match" & (matchCount))
             Dim i As Integer
             For i = 1 to 2
                Dim g as Group = m.Groups(i)
                Console.WriteLine("Group" & i & "='" & g.ToString() & "'")
                Dim cc As CaptureCollection = g.Captures
                Dim j As Integer 
                For j = 0 to cc.Count - 1
                  Dim c As Capture = cc(j)
                   Console.WriteLine("Capture" & j & "='" & c.ToString() _
                      & "', Position=" & c.Index)
                Next 
             Next 
             m = m.NextMatch()
          Loop
       End Sub
    End Module
    

提交回复
热议问题