Home > Enterprise >  Regular Expression to remove between characters (Excel VBA)
Regular Expression to remove between characters (Excel VBA)

Time:10-04

I have some text I need remove from a string, but I cannot use the normal Replace() because it is a timestamp that will always be changing.

Text to remove <09:35:40> (could be any time, but always the same format <HH:MM:SS>).

These time stamps could occur in multiple locations throughout a string, all need to be removed (replaced with "").

I've seen regular expressions used for similar applications on other posts, but I don't really understand them, so cannot validate which one to use for my use case here.

Edit: The < and > also need to be removed.

If feedback could be provided as to the -1, that would be great. Help me improve.

CodePudding user response:

You don't need regular expressions I don't think. What about:

Range("A:A").Replace "<??:??:??>", "", xlPart
  • Use Application.Trim() to deal with double spaces after replacement;
  • Range("A:A") is just my placeholder for whatever is your range-object.

CodePudding user response:

Use this regular expression to select all the sub strings in HH:MM:SS format. Then just replace it with empty string ("")

\d\d:\d\d:\d\d

And use this one to remove select it including these characters <>

\<\d\d:\d\d:\d\d\>

CodePudding user response:

You could use Split:

Text = "Text to remove <09:35:40> (could be any time, but always the same format)"
NewText = Split(Text, "<")(0)   Split(Text, "> ")(1)

? NewText
Text to remove (could be any time, but always the same format)

CodePudding user response:

Dim regExp As ObjectSet reg
Exp = CreateObject("vbscript.regexp")
        
With regExp
     .Global = True      'Get all matches.
     .Pattern = "\<\d\d:\d\d:\d\d\>"
     newString = .Replace(prevString, "")
End With
  • Related