Click here to Skip to main content
14,669,305 members
Rate this:
Please Sign up or sign in to vote.
See more:
Good day. I am beginner to vbscripting & need some assistance in getting my code right. I have got a code that search for word in a text file that has "89" and got to return only the full word. My code currently returns the whole line/sentence.

code >>>

Const ForReading = 1

Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Pattern = "89"

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objFile = objFSO.OpenTextFile("C:\Temp\test.txt", ForReading)

Do Until objFile.AtEndOfStream

strSearchString = objFile.ReadLine

Set colMatches = objRegEx.Execute(strSearchString)

If colMatches.Count > 0 Then

For Each strMatch in colMatches

Wscript.Echo strSearchString


End If



<<< code

test.txt file >>

Ready information for interface Cellular:
State : Ready to power up and register
Emergency mode : Off
Subscriber Id : 655020007620408
SIM ICC Id : 89270200150007090909
Number of telephone numbers : 0

What I have tried:

expected output > 89270200150007090909

currently output > SIM ICC Id : 89270200150007090909
Updated 22-Aug-17 2:10am

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

This is not only a VbScript problem but also a regex problem.

The first error is a mistake in your script:
For Each strMatch in colMatches
    Wscript.Echo strSearchString
You are printing strSearchString (the line read from the file) instead of strMatch (each match).

To get only the matched parts, enclose them with parentheses. But that requires to include the following characters until a word separation character occurs. In your case you can simply match for "89" followed by one or more digits:
objRegEx.Pattern = "(89\d+)"
If you know that the total length is always 20, you can also specify that there must be 18 following digits:
objRegEx.Pattern = "(89\d{18})"

See also Regular Expression Syntax (Scripting)[^].

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100