2

How can I pull the string that match regex pattern.

String = "Someting 1245:1000, someting 45678:2000, someting 100:1234"

I need only 1245, 45678, 100 just before the ":"

Sub short() 

  Dim RegEx As Object, MyString As String
  Dim match1 As Variant
    Set RegEx = CreateObject("VBScript.RegExp")

    With RegEx
      .Pattern = "^[\d\d\d\d:\d\d\d\d]"
    End With
end sub
1
  • Wouldn't (\d+)\: work for this (capture one or more digits that are immediately followed by a colon)? Commented Oct 25, 2022 at 14:47

1 Answer 1

3

You can use

Sub short()
  Dim RegEx As RegExp, MyString As String
  Dim m As Match, Matches as MatchCollection

  MyString = "Someting 1245:1000, someting 45678:2000, someting 100:1234"
  Set RegEx = New RegExp

  With RegEx
    .pattern = "\d+(?=:\d{4})"
    .Global = True
  End With

  Set Matches = RegEx.Execute(MyString)

  If Matches.Count > 0 Then
    For Each m In Matches
      Debug.Print m.Value
    Next
  End If

End Sub

See the debug output:

enter image description here

Regex details:

  • \d+ - one or more digits
  • (?=:\d{4}) - a positive lookahead that matches a location that is immediately followed with : and four digits

See the regex demo.

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

Comments

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.