Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA excel for finding digit pattern in the string

Tags:

regex

excel

vba

I was able to write a code which finds 6 digit numbers within the string and copy it into next column but I would like to add search which also can find numbers with pattern ##-#### and copy it into next column, example below:

Example

Can somebody help me?

Sub Pull_6_Digit_Numbers_From_String()


   Dim r As Range, i As Long
    With CreateObject("VBScript.RegExp")
        .Global = True
        .Pattern = "\b\d{6}\b"
        For Each r In Range("A1", Range("A" & Rows.Count).End(xlUp))
            If .test(r.Value) Then
                For i = 0 To .Execute(r.Value).Count - 1
                    r(, i + 2).Value = .Execute(r.Value)(i)
                Next
            End If
        Next
    End With
like image 577
FotoDJ Avatar asked Mar 18 '26 00:03

FotoDJ


1 Answers

Your current pattern, \b\d{6}\b, matches a word boundary, then 6 consecutive digits and then again a word boundary. So, it matches 123456 in text 123456 here. To also match 12-3456, you may split the pattern into 2- and 4-digit subpatterns and insert an optional - pattern, -?.

\b\d{2}-?\d{4}\b

See the regex demo

The -? matches 1 or 0 hyphens, and \d{2} with \d{4} will match 6 digits between word boundaries all in all.

like image 150
Wiktor Stribiżew Avatar answered Mar 20 '26 14:03

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!