Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract Excel string from matched Regular Expression (VBA)

Tags:

regex

excel

vba

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 ;)

like image 264
Jose A Avatar asked Dec 14 '22 15:12

Jose A


2 Answers

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
like image 51
Rory Avatar answered Jan 18 '23 10:01

Rory


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
like image 45
brettdj Avatar answered Jan 18 '23 11:01

brettdj