3

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
2
  • Do you mean you want to extend your current pattern? Try \b\d{2}-?\d{4}\b Commented Aug 17, 2017 at 14:12
  • Are you having trouble coming up with the pattern? Commented Aug 17, 2017 at 14:13

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Got it, Thank you Wiktor for clear and transparent explanation!
Wiktor, is there a way to pull the text with starts with capital N and will have combination of 3 to 6 letters or numbers with it ie. N24 or NX747 or N35655V but it should ignore N2 or N8(N plus 1 character) or N1234567(N plus more than 6 characters?
@FotoDJ: It seems you want either \bN[^\W_]{3,6}\b or \bN[^\W_]{2,6}\b.
\bN[^\W_]{3,6}\b solves the problem, thanks a lot! it matches also N and lower case words like North, New etc, Is there a way to prevent matching lower case after N which would eliminate above matching problem, I promise this is the last question, you 've been a great help, Wiktor.
It is brilliant again.THANK YOU.
|

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.