Reputation: 3
Hoping for help on a regex replacement code in VBScript that matches the length of the string found. There are quite a few variations found on the web, but my skill level is not extensive so making sense of them has been a long and frustrating. Perhaps I'm using the wrong tool, not sure anymore.
The challenge is adjusting a field in a fixed length file which is not formatted correctly for the recipient. There is a field that contains text of variable length, a dash, and more text. The variable length string and the dash need to each be replaced with a space. This will maintain the positioning in the fixed-width file.
The regex I put together is: strOriginal = "\b([A-Z0-9]{2,4}[-])"
This is working well for the data file matches. Can an expert guide me in the correct replacement?
Thank you, Drew
Upvotes: 0
Views: 1703
Reputation: 70961
You need to use a replace function for your regular expression
Option Explicit
Function replaceFunction(matchString, position, fullString)
replaceFunction = Space(Len(matchString))
End Function
Dim originalString
originalString = "W 121ST ST 3A8-2B"
Dim changedString
With New RegExp
.Global = True
.Pattern = "\b[A-Z0-9]{2,4}-"
changedString = .Replace( originalString, GetRef("replaceFunction") )
End With
WScript.Echo "[" & originalString & "]"
WScript.Echo "[" & changedString & "]"
The function arguments are the string section that matches the pattern in the regular expression, the position in the input string where the match has been found and the full string being processed.
In your case, for each match, the function is called and it will return a spaces string, the same length that the matching string.
EDITED to adapt to comments
Option Explicit
Function replaceFunction(matchString, prefix, toSpaces, position, fullString)
replaceFunction = prefix & Space(Len(toSpaces))
End Function
Dim originalString
originalString = "W 121ST ST 3A8-2B" & vbCRLF & "W 12-ST ST 3A8-2B"
Dim changedString
With New RegExp
.Global = True
.Multiline = True
.Pattern = "^(.{10,}\b)([A-Z0-9]{2,4}-)"
changedString = .Replace( originalString, GetRef("replaceFunction") )
End With
WScript.Echo originalString
WScript.Echo changedString
Now it handles a multiline input, and for each of the lines, it searchs the first 10 (or more) characters, followed by the string to replace with spaces. The regular expression define two capture groups that are passed as arguments to the replace function. This function will return the first capture group (the prefix) followed by the adecuated number of spaces to replace the non needed string.
Upvotes: 2