LoveEnigma
LoveEnigma

Reputation: 113

VB: Read "x" integer from a string and replace it

First of all, I am not from programming background and totally new to VB. For some reasons, I have to do a small scripting task at office.

I have gone through many posts here as well on other forums but not able to find the required information.

Ok so here's what I need to do:

I want to find an integer from a string (the integer can be any from 5 to 4095) and replace it with an integer of my choice.

I have done some analysis but not able to find a function which can search for "any" integer from a string. Searching for fixed integers is working fine.

e.g:

Convert: "There are 10 apples" - where 10 can be any number from 5 to 4095, not known to me.

To: "There are 5 apples" - 5 is the number I will manually give.

Any help is appreciated.

Thank you.

Edit

Final Code:

Set objFSO = CreateObject("Scripting.FileSystemObject") 
strFile = "C:\Users\inkasap\Desktop\temp\IOParams_Backup.xml" 
Set objFile = objFSO.OpenTextFile(strFile) 
Do Until objFile.AtEndOfStream strLine = objFile.ReadLine 
    Dim re, strLine 
    Set re = New RegExp 
    if InStr(strLine,"name=""BIOSCUPP") > 0 Then 
        re.Pattern = "\d+" 
        Set colMatch = re.Execute(strLine) 
        For Each objMatch In colMatch 
           strLine = Replace(strLine, objMatch.Value, "30") 
        Next end 
    if WScript.Echo strLine 
Loop

Upvotes: 1

Views: 1235

Answers (2)

sloth
sloth

Reputation: 101052

Well, you can use regular expressions to find any numerical value, and then replace it:

Dim re, test
Set re = New RegExp
re.Pattern = "\d+"

test = "There are 4000 apples"

Set colMatch = re.Execute(test)
For Each objMatch In colMatch
    MsgBox(Replace(test,objMatch.Value,"5"))
Next 

enter image description here

This page contains all informations you need.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460098

You can use a RegularExpressions with Regex.Replace method:

Dim str = "There are 10 apples"
Dim regex = New System.Text.RegularExpressions.Regex("\d+", System.Text.RegularExpressions.RegexOptions.Compiled)
Dim replaced = regex.Replace(str, "5") ' "There are 5 apples" '

Edit: Just only seen that you need a vbscript instead of VB.NET approach.

Upvotes: 1

Related Questions