从匹配的正则表达式中提取Excel字符串(VBA)

4
我希望您能在Excel VBA中提取给定字符串中匹配的正则表达式模式。

例如,

给定此表达式:

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

从这个字符串中:

"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: e.g. 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"

我只想获取匹配的模式。我该怎么做?

非常感谢所有回复;)

2个回答

10
您可以使用以下内容:
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: e.g. 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

2
一些对Rory出色答案的小建议(假设您的初始函数中有冗余):
一些小建议可以提升Rory优秀答案的效果(如果你在最初的函数中已经实现了冗余):
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接