TESTEVERYTHING

Showing posts with label FileSystemObject. Show all posts
Showing posts with label FileSystemObject. Show all posts

Saturday, 17 September 2011

How to Use the VBScript RegExp Object

 

Hi All,

I faced a situation where I had to update the field’s value from another file. I can not use the string replace method because It will replace the all the matches value, While I want to replace the first match with the first value of another file.  Here I am trying to explain

First File Contents:

This blog refers to QTP.
I want to get first line value "="  from another file.
Here I am using Rexexp
with global property value false
Now I want to get Second line value "="  from another file.
Global property false will serach only first match
If regexp global property true then it search all the matches
Now I want to get Third line value "="  from another file.


Second File Contents:

Rajiv
Kumar
Nandvani


I want output like this:

This blog refers to QTP.
I want to get first line value "Rajiv"  from another file.
Here I am using Rexexp
with global property value false
Now I want to get Second line value "Kumar"  from another file.
Global property false will serach only first match
If regexp global property true then it search all the matches
Now I want to get Third line value "Nandvani"  from another file.



Here is the code that I used to solve this problem

Function GetReplaceFirstMatch(PatternToMatch, byref StringToSearch,valuetoreplace)
 Set myRegExp = New RegExp
 myRegExp.IgnoreCase = True
 myRegExp.Global = False
 myRegExp.Pattern = PatternToMatch

 GetReplaceFirstMatch = myRegExp.Replace(StringToSearch,valuetoreplace)

end Function
Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")


Set objFile = objFSO.OpenTextFile("C:\FirstFile.txt", ForReading)
subjectString= objFile.ReadAll

Set objTestFile = objFSO.OpenTextFile("C:\SecondFile.txt", ForReading)


Do Until objTestFile.AtEndOfStream

    strLineRead = objTestFile.ReadLine
            subjectString = GetReplaceFirstMatch("=",subjectString,strLineRead)
           

Loop
const ForWriting = 2
Set objResultFile = objFSO.CreateTextFile("C:\resultTestfile.txt", ForWriting)

objResultFile.write subjectString

How to Use the VBScript RegExp Object

You can use regular expressions in VBScript by creating one or more instances of the RegExp object. This object allows you to find regular expression matches in strings, and replace regex matches in strings with other strings. The functionality offered by VBScript's RegExp object is pretty much bare bones. However, it's more than enough for simple input validation and output formatting tasks typically done in VBScript.
The advantage of the RegExp object's bare-bones nature is that it's very easy to use. Create one, put in a regex, and let it match or replace. Only four properties and three methods are available.
After creating the object, assign the regular expression you want to search for to the Pattern property. If you want to use a literal regular expression rather than a user-supplied one, simply put the regular expression in a double-quoted string. By default, the regular expression is case sensitive. Set the IgnoreCase property to True to make it case insensitive. The caret and dollar only match at the very start and very end of the subject string by default. If your subject string consists of multiple lines separated by line breaks, you can make the caret and dollar match at the start and the end of those lines by setting the Multiline property to True. VBScript does not have an option to make the dot match line break characters. Finally, if you want the RegExp object to return or replace all matches instead of just the first one, set the Global property to True.
'Prepare a regular expression object
Set myRegExp = New RegExp
myRegExp.IgnoreCase = True
myRegExp.Global = True
myRegExp.Pattern = "regex"
After setting the RegExp object's properties, you can invoke one of the three methods to perform one of three basic tasks. The Test method takes one parameter: a string to test the regular expression on. Test returns True or False, indicating if the regular expression matches (part of) the string. When validating user input, you'll typically want to check if the entire string matches the regular expression. To do so, put a caret at the start of the regex, and a dollar at the end, to anchor the regex at the start and end of the subject string.
The Execute method also takes one string parameter. Instead of returning True or False, it returns a MatchCollection object. If the regex could not match the subject string at all, MatchCollection.Count will be zero. If the RegExp.Global property is False (the default), MatchCollection will contain only the first match. If RegExp.Global is true, Matches> will contain all matches.
The Replace method takes two string parameters. The first parameter is the subject string, while the second parameter is the replacement text. If the RegExp.Global property is False (the default), Replace will return the subject string with the first regex match (if any) substituted with the replacement text. If RegExp.Global is true, Replace will return the subject string with all regex matches replaced.
You can specify an empty string as the replacement text. This will cause the Replace method to return the subject string will all regex matches deleted from it. To re-insert the regex match as part of the replacement, include $& in the replacement text. E.g. to enclose each regex match in the string between square brackets, specify [$&] as the replacement text. If the regexp contains capturing parentheses, you can use backreferences in the replacement text. $1 in the replacement text inserts the text matched by the first capturing group, $2 the second, etc. up to $9. To include a literal dollar sign in the replacements, put two consecutive dollar signs in the string you pass to the Replace method.

Getting Information about Individual Matches

The MatchCollection object returned by the RegExp.Execute method is a collection of Match objects. It has only two read-only properties. The Count property indicates how many matches the collection holds. The Item property takes an index parameter (ranging from zero to Count-1), and returns a Match object. The Item property is the default member, so you can write MatchCollection(7) as a shorthand to MatchCollection.Item(7).
The easiest way to process all matches in the collection is to use a For Each construct, e.g.:
' Pop up a message box for each match
Set myMatches = myRegExp.Execute(subjectString)
For Each myMatch in myMatches
  msgbox myMatch.Value, 0, "Found Match"
Next
The Match object has four read-only properties. The FirstIndex property indicates the number of characters in the string to the left of the match. If the match was found at the very start of the string, FirstIndex will be zero. If the match starts at the second character in the string, FirstIndex will be one, etc. Note that this is different from the VBScript Mid function, which extracts the first character of the string if you set the start parameter to one. The Length property of the Match object indicates the number of characters in the match. The Value property returns the text that was matched.
The SubMatches property of the Match object is a collection of strings. It will only hold values if your regular expression has capturing groups. The collection will hold one string for each capturing group. The Count property indicates the number of string in the collection. The Item property takes an index parameter, and returns the text matched by the capturing group. The Item property is the default member, so you can write SubMatches(7) as a shorthand to SubMatches.Item(7). Unfortunately, VBScript does not offer a way to retrieve the match position and length of capturing groups.
Also unfortunately is that the SubMatches property does not hold the complete regex match as SubMatches(0). Instead, SubMatches(0) holds the text matched by the first capturing group, while SubMatches(SubMatches.Count-1) holds the text matched by the last capturing group. This is different from most other programming languages. E.g. in VB.NET, Match.Groups(0) returns the whole regex match, and Match.Groups(1) returns the first capturing group's match. Note that this is also different from the backreferences you can use in the replacement text passed to the RegExp.Replace method. In the replacement text, $1 inserts the text matched by the first capturing group, just like most other regex flavors do. $0 is not substituted with anything but inserted literally.


VBScript Find First Match By Regular Expression Utility Function


' Get the first regex submatch from the string
' Returns empty string if not found, otherwise returns the matched string
Function GetFirstMatch(PatternToMatch, StringToSearch)
 Dim regEx, CurrentMatch, CurrentMatches

 Set regEx = New RegExp
 regEx.Pattern = PatternToMatch
 regEx.IgnoreCase = True
 regEx.Global = True
 regEx.MultiLine = True
 Set CurrentMatches = regEx.Execute(StringToSearch)

 GetFirstMatch = ""
 If CurrentMatches.Count >= 1 Then
  Set CurrentMatch = CurrentMatches(0)
  If CurrentMatch.SubMatches.Count >= 1 Then
   GetFirstMatch = CurrentMatch.SubMatches(0)
  End If
 End If
 Set regEx = Nothing
End Function

' Example
' Parse out the database name from a SQL server database connection string
Function GetDatabaseName(ByVal DSNString)
 GetDatabaseName = GetFirstMatch(".*Initial Catalog=(.*);", DSNString)
End Function

VBScript Replace All Matches By Regular Expression Utility Function


' Replace all matches in the string with the replacement text
Sub ReplaceAllByExpression(ByRef StringToExtract, ByVal MatchPattern, _
 ByVal ReplacementText)
 Dim regEx, CurrentMatch, CurrentMatches

 Set regEx = New RegExp
 regEx.Pattern = MatchPattern
 regEx.IgnoreCase = True
 regEx.Global = True
 regEx.MultiLine = True
 StringToExtract = regEx.Replace(StringToExtract, ReplacementText)
 Set regEx = Nothing

End Sub

' Example
' Remove all images from an HTML page
ReplaceAllByExpression HTMLPageData, "<img[^<]*?>", "" 
 

Saturday, 25 June 2011

Adding Data to the File Working with files(FileSystemObject) / QTP

Adding Data to the File

Once the text file is created, add data to the file using the following three steps:
Open the text file.
Write the data.
Close the file.
To open an existing file, use either the OpenTextFile method of the FileSystemObject object or the OpenAsTextStream method of the File object.
To write data to the open text file, use the Write, WriteLine, or WriteBlankLines methods of the TextStream object, according to the tasks outlined in the following table
Task
Method
Write data to an open text file without a trailing newline character.      
Write
Write data to an open text file with a trailing newline character.
WriteLine
Write one or more blank lines to an open text file.
WriteBlankLines
To close an open file, use the Close method of the TextStream object.
Note The newline character contains a character or characters (depending on the operating system) to advance the cursor to the beginning of the next line (carriage return/line feed). Be aware that the end of some strings may already have such nonprinting characters.
The following example demonstrates how to open a file, use all three write methods to add data to the file, and then close the file:
[VBScript]
Sub CreateFile()
   Dim fso, tf
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set tf = fso.CreateTextFile("c:\testfile.txt", True)
   ' Write a line with a newline character.
   tf.WriteLine("Testing 1, 2, 3.") 
   ' Write three newline characters to the file.        
   tf.WriteBlankLines(3) 
   ' Write a line.
   tf.Write ("This is a test.") 
   tf.Close
End Sub

Creating Files Working with files(FileSystemObject) / QTP

Creating Files

There are three ways to create an empty text file (sometimes referred to as a “text stream”).
The first way is to use the CreateTextFile method. The following example demonstrates how to create a text file using the CreateTextFileMethod method.
[VBScript]
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
[JScript]
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile("c:\\testfile.txt", trThe second way to create a text file is to use the OpenTextFile method of the
FileSystemObject object with the ForWriting flag set.
[VBScript
Dim fso, ts
Const ForWriting = 2
Set fso = CreateObject("Scripting. FileSystemObject")
Set ts = fso.OpenTextFile("c:\test.txt", ForWriting, True)
[JScript]var fso, ts;var ForWriting= 2;fso = new ActiveXObject("Scripting.FileSystemObject")ts = fso.OpenTextFile("c:\\test.txt", ForWriting, true);
A third way to create a text file is to use the OpenAsTextStream method with the ForWriting flag set.
[VBScript]
Dim fso, f1, ts
Const ForWriting = 2
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateTextFile ("c:\test1.txt")
Set f1 = fso.GetFile("c:\test1.txt")
Set ts = f1.OpenAsTextStream(ForWriting, True

Translate







Tweet