使用RegEx在字符串中查找匹配的特定实例

时间:2015-08-11 20:24:53

标签: regex ms-access

我是RegEx的新手,我似乎无法找到我想要的东西。我有一个字符串,如:

[cmdSubmitToDatacenter_Click] in module [Form_frm_bk_UnsubmittedWires]

我希望得到第一组括号内的所有内容以及第二组括号。如果有一种方法我可以用一种模式做到这一点,这样我就可以循环匹配,这将是很棒的。如果没有,那很好。我只需要能够分别获取文本的不同部分。到目前为止,以下是我提出的所有内容,但它只返回整个字符串减去第一个左括号和最后一个右括号:

[\[-\]]

(注意:我使用了替换功能,所以这可能与你期望的相反。)

在我的研究中,我发现有不同的RegEx引擎。我不确定我使用的名称,但我在MS Access中使用它。

2 个答案:

答案 0 :(得分:2)

如果您使用的是Access,则可以使用VBScript Regular Expressions Library执行此操作。例如:

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

输出:

cmdSubmitToDatacenter_Click
Form_frm_bk_UnsubmittedWires

答案 1 :(得分:1)

这是我最终使用的内容,因为它更容易获得返回的单个值。我设置了对Microsoft VBScript Regular Expression 5.5的引用,以便我可以获得Intellisense帮助。

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