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 ;)
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With