1

I am very new to RegEx and I can't seem to find what I looking for. I have a string such as:

[cmdSubmitToDatacenter_Click] in module [Form_frm_bk_UnsubmittedWires]

and I want to get everything within the first set of brackets as well as the second set of brackets. If there is a way that I can do this with one pattern so that I can just loop through the matches, that would be great. If not, thats fine. I just need to be able to get the different sections of text separately. So far, the following is all I have come up with, but it just returns the whole string minus the first opening bracket and the last closing bracket:

[\[-\]]

(Note: I'm using the replace function, so this might be the reverse of what you are expecting.)

In my research, I have discovered that there are different RegEx engines. I'm not sure the name of the one that I'm using, but I'm using it in MS Access.

Bond
  • 16,071
  • 6
  • 30
  • 53
kb9zzo
  • 21
  • 4
  • Please post the whole relevant code here. Isn't it VBA (Visual Basic for Applications)? BTW, even in VBA, `[\[-\]]` is not something that will match the whole string (it can match just 1 character). So, with replace, you will get `cmdSubmitToDatacenter_Click in module Form_frm_bk_UnsubmittedWires`. Try `(\[[^\[\]]*]).*` regex and use `$1` in the replacement. – Wiktor Stribiżew Aug 11 '15 at 20:29
  • See this thread: http://stackoverflow.com/questions/2403122/regular-expression-to-extract-text-between-square-brackets – Charlie Haley Aug 11 '15 at 20:37
  • I never did come across that thread. Thanks for providing it. – kb9zzo Aug 12 '15 at 13:15

2 Answers2

2

If you're using Access, you can use the VBScript Regular Expressions Library to do this. For example:

Const SOME_TEXT = "[cmdSubmitToDatacenter_Click] in module [Form_frm_bk_UnsubmittedWires]"

Dim re
Set re = CreateObject("VBScript.RegExp")
re.Global = True
re.Pattern = "\[([^\]]+)\]"

Dim m As Object
For Each m In re.Execute(SOME_TEXT)
    Debug.Print m.Submatches(0)
Next

Output:

cmdSubmitToDatacenter_Click
Form_frm_bk_UnsubmittedWires
Bond
  • 16,071
  • 6
  • 30
  • 53
1

Here is what I ended up using as it made it easier to get the individual values returned. I set a reference to the Microsoft VBScript Regular Expression 5.5 so that I could get Intellisense help.

Public Sub GetText(strInput As String)
Dim regex As RegExp
Dim colMatches As MatchCollection
Dim strModule As String
Dim strProcedure As String

Set regex = New RegExp

With regex
    .Global = True
    .Pattern = "\[([^\]]+)\]"
End With

Set colMatches = regex.Execute(strInput)

With colMatches
    strProcedure = .Item(0).submatches.Item(0)
    strModule = .Item(1).submatches.Item(0)
End With

Debug.Print "Module: " & strModule
Debug.Print "Procedure: " & strProcedure

Set regex = Nothing
End Sub
kb9zzo
  • 21
  • 4