1

I have this input string:

Hello <foo> context61 Hi: context:file/  hello context715: context666:file/ foo

My goal is replace (clean) every occurrence of context[anything]: to an empty string. the anything part could be empty.

Output should look like this:

Hello <foo> context61 Hi: file/  hello  file/ foo

I have tried endless attempts but I'm just a noob when it comes to regex. Can anyone help please?

1 Answer 1

7

Give a try to the following vbscript code:

str="Hello <foo> context61 Hi: context:file/  hello context715: context666:file/ foo"
Set oreg = New RegExp
oreg.IgnoreCase=False
oreg.Global=True
oreg.Pattern="context\d*\:"                'context followed by 0 or more digits followed by colon
'oreg.Pattern="context[a-zA-Z0-9]*?\:"     'or we can have this as pattern which will cover alphabets too
result = oreg.Replace(str,"")              'replaces every matched pattern in the string 'str' by an empty string
MsgBox result

Output:

enter image description here

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

7 Comments

"Set matches = oreg.Execute(str)" is not necessary.
@RegisDesrosiers You are correct. I was testing the matches first. Forgot to remove it. I will update the code.
"oreg.IgnoreCase=False" could also be removed also because .IgnoreCase is false by default.
@Kira, BTW, would it be more efficient to first test? e.g.: If oreg.Test(str) Then oreg.Replace...
@zig Yes, By using an If statement you can first test if a match is there or not. If it returns true, then replace otherwise don't replace. However, the current code won't throw you an error even if there are no matches.
|

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.