Muzammil
Muzammil

Reputation: 668

VBA RegEx getting String with only Number and Hyphen

I have a string with something like
Bl. 01 - 03

I want this to be reduced to only
01-03

Everything other than digits & hyphen should be removed. Any ideas how to do it using or any other method?

Upvotes: 3

Views: 4021

Answers (3)

Mallard
Mallard

Reputation: 308

Here's a function with a non-RegEx approach to remove anything but digits and the hyphen from a given input string:

Function removeBadChars(sInput As String) As String
    Dim i As Integer
    Dim sResult As String
    Dim sChr As String

    For i = 1 To Len(sInput)
        sChr = Mid(sInput, i, 1)
        If IsNumeric(sChr) Or sChr = "-" Then
            sResult = sResult & sChr
        End If
    Next

    removeBadChars = sResult
End Function

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89629

you can use this pattern in a replace expression:

reg.Pattern = "[^\d-]+"
Debug.Print reg.Replace(yourstring, "")

Upvotes: 3

femtoRgon
femtoRgon

Reputation: 33351

Barring a more complete description of exactly what you mean by something like "BI. 01 - 03", this:

^.*(\d{2}\s?-\s?\d{2}).*$

Will capture the portion you seem to be interested in as group 1. If you want to get rid of the spaces as well, then something like:

^.*(\d{2})\s?-\s?(\d{2}).*$

might be more suited, where you will have the two numbers in groups 1 and 2, and can replace the hyphen in output.

Upvotes: 0

Related Questions