1

I'm reading a text file in VbScript line by line and storing the value each time in a variable called line_text.

The line_text variable can take values as
":60F:C180235P56987456"
":60M:C184535P56987456"
":60F:D182335P56987456"
":60M:D180278P56987456"

As per my solution, I had used four regex expressions as follows:

Set fso = CreateObject(“Scripting.FileSystemObject”)
Set objFileToRead=fso.OpenTextFile("C:\New\maddy.txt",1) 
Set objFileToWrite=fso.OpenTextFile("C:\New\maddy1.txt",2,true) 

Dim line_text
Set re1 = New RegExp
re1.Pattern = "(:60F:C)\d{6}"

Set re2 = New RegExp
re2.Pattern = "(:60M:C)\d{6}"

Set re3 = New RegExp
re3.Pattern = "(:60F:D)\d{6}"

Set re4 = New RegExp
re4.Pattern = "(:60M:D)\d{6}"

patt1=":60F:C120412"
patt2=":60M:C120412"
patt3=":60F:D120412"
patt4=":60M:D120412"

do until objFileToRead.AtEndOfStream Then
    line_text = objFileToRead.ReadLine()
    If re1.test(line_text) Then
        line_text=re1.replace(line_text,patt1)
    ElseIf re2.test(line_text) Then
        line_text=re2.replace(line_text,patt2)
    ElseIf re3.test(line_text) Then
        line_text=re3.replace(line_text,patt3)
    ElseIf re4.test(line_text) Then
        line_text=re4.replace(line_text,patt4)
    End If

    objFileToWrite.Write(line_text)
Loop
Set objFileToRead = Nothing
Set objFileToWrite = Nothing

As I want to replace the six digits followed by a character in the sub-string with same string "120412", what will be the best possible way for making the replacement without using four different expressions as I used. This is totally time consuming.

Is there any grouping facility available here in VBScript so that I can group those six digits for all line read operations in a single expression and replace all with same expression "120412" as it's repeating.

1 Answer 1

1

You may use a single pattern:

:60([FM]):([CD])\d{6}

and replace with a single replacement pattern:

:60$1:$2120412

See the regex demo

Details

  • :60 - a literal :60 substring
  • ([FM]) - Capturing group 1: a F or M
  • : - a colon
  • ([CD]) - Capturing group 2: a C or D
  • \d{6} - six digits.

The $1 stands for the value captured in Capturing group 1 and $2 is the placeholder containing text captured with Capturing group 2.

VB Script test:

Dim s As String
Dim regex As Object

s = ":60F:C180235P56987456" & vbCrLf & ":60M:C184535P56987456" & vbCrLf & ":60F:D182335P56987456" & vbCrLf & ":60M:D180278P56987456"
Set regex = CreateObject("VBScript.RegExp")
With regex
  .Pattern = ":60([FM]):([CD])\d{6}"
  .Global = True
End With

wscript.echo regex.Replace(s, ":60$1:$2120412")

Output:

:60F:C120412P56987456
:60M:C120412P56987456
:60F:D120412P56987456
:60M:D120412P56987456
Sign up to request clarification or add additional context in comments.

Comments