从匹配的正则expression式(VBA)中提取Excelstring

我想从Excel VBA中的给定string中提取匹配的RegExp模式。

例如,

给出这个expression式:

"[0-9]*\+[0-9]{3}\@[0-9]*\+[0-9]{3}" 

从这个string:“CSDT2_EXC_6 + 000 @ 6 + 035_JM_150323”

我想得到:“6 + 000 @ 6 + 035”

但我不知道如何做到这一点。

最近我能得到的是这样的:

 Function getStations(file_name As String) 'Use Regular Expressiosn for grabbing the input and automatically filter it Dim regEx As New RegExp With regEx .Global = True .MultiLine = True .IgnoreCase = True 'This matches the pattern: eg 06+900@07+230 .Pattern = "[0-9]*\+[0-9]{3}\@[0-9]*\+[0-9]{3}" End With If regEx.Test(file_name) Then strReplace = "" getStations = regEx.Replace(file_name, strReplace) Else getStations = "Hay un problema con el nombre. Por favor, arréglalo" End If End Function 

但这会给我带来以下:“CSDT2_EXC__JM_150323”

我只想采取匹配的模式。 我怎样才能做到这一点?

万分感谢所有答复;)

你可以使用这个:

 Function getStations(file_name As String) 'Use Regular Expressiosn for grabbing the input and automatically filter it Dim regEx As New RegExp With regEx .Global = True .MultiLine = True .IgnoreCase = True 'This matches the pattern: eg 06+900@07+230 .Pattern = "[0-9]*\+[0-9]{3}\@[0-9]*\+[0-9]{3}" End With If regEx.Test(file_name) Then getStations = regEx.Execute(file_name)(0) Else getStations = "Hay un problema con el nombre. Por favor, arréglalo" End If End Function 

对Rory的优秀答案有一些小小的build议(因为你在初始function上有冗余):

 Function getStations(file_name As String) As String 'Use Regular Expressionn for grabbing the input and automatically filter it Dim regEx As Object Set regEx = CreateObject("vbscript.regexp") regEx.Pattern = "[0-9]*\+[0-9]{3}\@[0-9]*\+[0-9]{3}" If regEx.Test(file_name) Then getStations = regEx.Execute(file_name)(0) Else getStations = "Hay un problema con el nombre. Por favor, arréglalo" End If End Function