Creating a regex to check number of occurence - vbscript

I want to check how many times this sequence occurs in a webpage in UFT (012345). Basically any 6 digits in between left parenthesis and right parenthesis. I want to figure out how times this (012345) occurs in the page.
What I have so far is:
Set myReg = new regexp
myReg.pattern = '(' [0-9]+ ')'
Set k = Browser("My Webpage).Page("My Index").ChildObjects(myReg)
msgbox k.count
This doesn't work. Could someone put me in the right path?

Read reference:
Regular Expression Syntax (Scripting) and
Regular Expression Object Properties and Methods (VBScript)
Next pure VBScript code snippet could help:
sText = "(123456) (123) (abcdef)" ' !!! retrieve web page source text here !!!
' instead of testing sample
Set regEx = New RegExp ' Create regular expression
regEx.Pattern = "\([0-9]{6}\)" ' Set pattern
regEx.IgnoreCase = True ' Set case sensitivity: superabundant for numbers
regEx.Global = True ' Set global applicability: all occurrences
Set oMatches = regEx.Execute(sText) ' Execute search
RegExpCountr = oMatches.Count '
msgbox RegExpCountr

Related

Validating a string vbscript

I am trying to search a string to make sure it does not contain a numbers followed by a comma followed by numbers and containing a dot and 2 decimal places, e.g. 32,000.00. At the moment, I have it searching to see if the string contains a dot only. How do I go about searching the criteria above?
Root_RefundAmount = Root_TaxDataSummary.SlvObject("RefundAmount").GetROProperty("text")
refund = InStr(1,Root_RefundAmount,".")
If refund > 0 Then
pass
Else
fail
End If
I believe a simple Regular Expression Test will provide you what you want:
Dim objRegEx, strValue
'Create Regular Expression object to parse the file
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.IgnoreCase = True
objRegEx.Global = True
objRegEx.MultiLine = True
objRegEx.Pattern = "\d+\,\d+\.\d{2}"
strValue = "e.g. 32,000.00."
MsgBox objRegEx.test(strValue) '<- True
strValue = "e.g. 3200000."
MsgBox objRegEx.test(strValue) '<- False
The above will result in a Boolean response (True/False).
Adapting it to your routine...
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.IgnoreCase = True
objRegEx.Global = True
objRegEx.MultiLine = True
objRegEx.Pattern = "\d+\,\d+\.\d{2}"
Root_RefundAmount = Root_TaxDataSummary.SlvObject("RefundAmount").GetROProperty("text")
If Not objRegEx.test(Root_RefundAmount) Then
'Pattern NOT Found
Else
'Pattern IS Found
End If
To explain the Pattern:
"\d+\,\d+\.\d{2}"
\d = Any Number 0 through 9...
"A numbers followed by a comma followed by numbers and containing a dot and 2 decimal places"{Assume you mean 2 Numbers}... Depending on your input the above is much easier to look at but it will also match numbers such as 12345,12345.99 which may or may not be desirable.
If you need to be precise then you may want to consider the below Regex:
"\d{1,3}(?:\,\d{3})*\.\d{2}"
This will match numbers from 0.00 to 999,999,999.99 etc in typical numeric format...
If you want to specifically look for numbers above 1,000 (With a Comma) Then change the Star '*' to a Plus '+' to mean One or More are Required...
"\d{1,3}(?:\,\d{3})+\.\d{2}"
Or for an even more specific Regex:
(?:[1-9]|[1-9][0-9]|[1-9][0-9]{2})(?:\,[0-9]{3})+\.[0-9]{2}
'OR
(?:[1-9]|[1-9]\d|[1-9]\d{2})(?:\,\d{3})+\.\d{2}
For a little more info on Regular Expressions and the '\d' Character Class, Please take a look at the below links:
http://www.regular-expressions.info/shorthand.html
https://msdn.microsoft.com/en-us/library/20bw873z(v=vs.110).aspx#Anchor_9

Clean up lines from log file

I have a file "D:\test.log" that has either one of two styles. This will appear if the user is offline when the user received the message:
[02:19:47] Brother Aimbot (adama900): (Saved Thu Mar 31 05:15:09 2016)This is a test line
It will be like this if the user is online when the user received the message:
[02:19:47] Brother Aimbot (adama900): This is a test line
What I would like this to do is cut out the excess parts so it would look like this if it's either the first or second style:
Brother Aimbot (adama900) This is a test line
then place it into a message box.
Here is my code:
Sub main()
filename = "D:\Test.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)
LNEVAL = f.ReadLine
LNENUM = 0
Do Until f.AtEndOfStream
For i = 1 To LNENUMs
f.ReadLine
Next
If InStr(LNEVAL, "(S") Then
LNEVAL = Left(LNEVAL, (Len("(S")+4))
MsgBox = LNEVAL
End If
Loop
f.Close
End Sub
This is what I have so far.
It's fairly simple to do what you want with a regular expression replacement. Basically what you want to do is remove three things from each line:
a substring between square brackets from the beginning of the string,
the colon separating the name from the message, and
an optional substring between parentheses after that colon.
A regular expression ^\[.*?\] matches an opening square bracket at the beginning of a string and the shortest number of characters up to a closing square bracket.
A regular expression \(Saved.*?\) matches an opening parenthesis followed by the word Saved and the shortest number of characters up to a closing parenthesis. However, since this part is optional you need to indicate that the expression can occur zero or one time by putting it in a non-capturing group and appending the ? modifier to it ((?:...)?).
Put the submatches that you do want to preserve in parentheses to create capturing groups
^\[.*?\] (.*?): (?:\(Saved.*?\))?(.*)
and replace each matching line with just the captured groups:
Set re = New RegExp
re.Pattern = ...
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
MsgBox re.Replace(f.ReadLine, "$1 $2")
Loop
f.Close
Some comments on your existing code:
For i = 1 To LNENUMs: this loop is always skipped over, because you set LNEUMs to 0. Since you only do f.ReadLine inside that For loop your outer Do loop becomes an infinite loop, since you never read the file to the end.
Len("(S")+4 always evaluates to 6, because the length of the string (S is not going to change, so you could just replace the expression with the numeric value.
MsgBox = LNEVAL: The MsgBox function doesn't work that way. Remove the = between function name and message.

Replace characters suing VB script

I want to replace a particular value followed by TRN* to some other value.How to do the coding for the same?..Please provide an example.
For example :
TRN*12345*34444~
This is a segment in my file(like this I have many TRN* segments in my file).I want to replace the segment after TRN* and before next * (ie.12345)with some other value.
Is there any way to do this by using vbscript?
Thanks in advance
The regular expression way of safetyOtter is the way to go, you only have to fiddle with the pattern and replacement string:
originalString = "TRN*12345*34444~"
replaceValue = "78910"
Set re = new RegExp
re.Pattern = "(.*TRN\*)([^*]+)(.*)"
re.IgnoreCase = False
' This keeps the first and last part between parenthesis, but replaces the middle part
newString = re.Replace(originalString, "$1" & replaceValue & "$3")
msgbox newString
' result: TRN*78910*34444~
Something like this should work, may have to tweak, can't test it at the moment
Set regEx = New RegExp
regEx.Pattern = "TRN\*.*?\*"
regEx.IgnoreCase = True
replStr = "TRN*" & SomeOtherValue& "*"
ReplaceTest = regEx.Replace(YourStringHere, replStr)
Edit:
if you are looking to replace a specific number with another, a simple:
YourStringHere = Replace(YourStringHere,"TRN*12345*","TRN*67890*")
Is enough

vbscript - Replace all spaces

I have 6400+ records which I am looping through. For each of these: I check that the address is valid by testing it against something similar to what the Post Office uses (find address). I need to double check that the postcode I have pulled back matches.
The only problem is that the postcode may have been inputted in a number of different formats for example:
OP6 6YH
OP66YH
OP6 6YH.
If Replace(strPostcode," ","") = Replace(xmlAddress.selectSingleNode("//postcode").text," ","") Then
I want to remove all spaces from the string. If I do the Replace above, it removes the space for the first example but leave one for the third.
I know that I can remove these using a loop statement, but believe this will make the script run really slow as it will have to loop through 6400+ records to remove the spaces.
Is there another way?
I didn't realise you had to add -1 to remove all spaces
Replace(strPostcode," ","",1,-1)
Personally I've just done a loop like this:
Dim sLast
Do
sLast = strPostcode
strPostcode = Replace(strPostcode, " ", "")
If sLast = strPostcode Then Exit Do
Loop
However you may want to use a regular expression replace instead:
Dim re : Set re = New RegExp
re.Global = True
re.Pattern = " +" ' Match one or more spaces
WScript.Echo re.Replace("OP6 6YH.", "")
WScript.Echo re.Replace("OP6 6YH.", "")
WScript.Echo re.Replace("O P 6 6 Y H.", "")
Set re = Nothing
The output of the latter is:
D:\Development>cscript replace.vbs
OP66YH.
OP66YH.
OP66YH.
D:\Development>
This is the syntax Replace(expression, find, replacewith[, start[, count[, compare]]])
it will default to -1 for count and 1 for start. May be some dll is corrupt changing the defaults of Replace function.
String.Join("", YourString.Split({" "}, StringSplitOptions.RemoveEmptyEntries))
Because you get all strings without spaces and you join them with separator "".

VB6 getting ride of large spaces

Hey all, i am trying to replace large spaces between text with just one. My output looks like this right now:
5964215">
This is just the first example of the spaces
5964478">
This would be the 2nd example of showing how many spaces this thing has in each sentence.
5964494">
That comes from a textbox that has multi-line to true. Here is what it looks like when it doesn't have multi-line to true.
http://www.june3rdsoftware.com/forums/vb6.jpg
I can not seem to get the spaces to go away! BTW, this text is from a webpage if that makes any difference.
David
According to the suggestion of MvanGeest, here is some VB code to replace blocks of white spaces:
Sub test()
Dim x As String, y As String
x = "abcd defg 1233"
Dim re As New RegExp
re.Pattern = "\s+"
re.Global = True
y = re.Replace(x, " ")
Debug.Print y
End Sub
To make this work, you will have to add a reference to "Microsoft VBScript Regular Expresssions" to your project.
Assuming no regex support, why not set up a simple state machine that will set the state=1 when a space is found and set state=0 once a non-space is encountered. You can move char by char when state=0 (thus copying over only 1 space per series of spaces).
Also assuming no regex, you could try something like
str = "long text with spaces "
i = LenB(str)
str = Replace(str, " ", " ")
Do While LenB(str) <> i
i = LenB(str)
str = Replace(str, " ", " ")
Loop
Of course this code could be optimized for long space sequences but it might be all you need as well

Resources