Author Topic: Search & Replace or RegEx Replace in VBSCript  (Read 4645 times)

Jayson

  • EA User
  • **
  • Posts: 363
  • Karma: +1/-0
    • View Profile
Search & Replace or RegEx Replace in VBSCript
« on: November 08, 2019, 10:58:32 am »
Hey all

I am using RegEx to find matches in string and then replace them.
The find match function seems to work, but the replace function does not.

I am using online generic VB Script language reference resources because I have never seen a Sparx specific one (might just never have seen it).
I am trying the following text and the output is "REGEX TEST = VAVAV", indicating that nothing has been replaced.

I have also tried the general string replace function and it doesn't seem to work either.

Any idea what my mistake is?

Cheers

Jays :-)


   Dim regex1
   Dim aString
   aString = "VAVAV"
   Set regex1 = new RegExp
   regex1.Global = true
   regex1.IgnoreCase = true
   regex1.Pattern = "V"
   regex1.Replace aString , "T"
   Session.Output "REGEX TEST = '" & aString
   

Geert Bellekens

  • EA Guru
  • *****
  • Posts: 13402
  • Karma: +566/-33
  • Make EA work for YOU!
    • View Profile
    • Enterprise Architect Consultant and Value Added Reseller
Re: Search & Replace or RegEx Replace in VBSCript
« Reply #1 on: November 08, 2019, 06:43:32 pm »
You are not using Replace correctly.
Both the regular Replace, as the regex Replace don't change anything to the string passed as parameter.
They return a new string with the results.

Here's an example:

Code: [Select]
Function cleanFileName(fileName)
Dim regEx
Set regEx = CreateObject("VBScript.RegExp")

regEx.IgnoreCase = True
regEx.Global = True
regEx.Pattern = "[(?*"",\\<>&#~%{}+@:\/!;]+"
cleanFileName = regEx.Replace(fileName, "-")
end function

Geert

Jayson

  • EA User
  • **
  • Posts: 363
  • Karma: +1/-0
    • View Profile
Re: Search & Replace or RegEx Replace in VBSCript
« Reply #2 on: November 11, 2019, 03:39:40 am »
Thanks Geert!

I always struggle with the fact that functions need brackets and subs don't, so I tried it as you described without the brackets and wondered what was going on!
All working now!

Cheers

Jays :-)