4

I would like to extract the matched RegExp pattern from a given string in Excel VBA.

For example,

Given this expression:

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

from this string: "CSDT2_EXC_6+000@6+035_JM_150323"

I'd like to get: "6+000@6+035"

But I don't know how to accomplish this.

The nearest I could get was this:

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

But this would bring me the following: "CSDT2_EXC__JM_150323"

I'd like to only take the matched pattern. How can I achieve this?

Thanks a million for all the replies ;)

2 Answers 2

10

You can use this:

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
Sign up to request clarification or add additional context in comments.

Comments

2

Some minor suggestions to Rory's excellent answer (given you have redundancy in your initial 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.