[Collapse]TestComplete/viewarticle/63445/
 [Expand]General Information/viewarticle/63445/
 [Expand]Using Help System/viewarticle/55799/
 [Expand]Getting Started Tutorial/viewarticle/56246/
 [Collapse]Using TestComplete/viewarticle/57875/
  [Expand]TestComplete User Interface, Projects and Settings/viewarticle/57876/
  [Collapse]Creating, Recording and Running Tests/viewarticle/56646/
   [Expand]Naming Objects/viewarticle/56265/
   [Expand]Creating Tests/viewarticle/57373/
   [Expand]Managing Tested Applications/viewarticle/57435/
   [Expand]Checkpoints and Stores/viewarticle/56266/
   [Expand]Running Tests/viewarticle/56462/
   [Expand]Handling Playback Errors/viewarticle/56641/
   [Expand]Keyword Testing/viewarticle/55462/
   [Collapse]Scripting/viewarticle/56245/
    [Collapse]Writing Scripts/viewarticle/56862/
      Writing Scripts - Overview/viewarticle/56520/
      Writing Scripts - Quick Start/viewarticle/58077/
      Selecting the Scripting Language/viewarticle/57892/
      Supported Scripting Languages - Specifics of Usage/viewarticle/57893/
      Calling Routines and Variables Declared in Another Unit/viewarticle/56539/
      Calling Routines Declared in Another Project/viewarticle/56535/
      Calling Methods Asynchronously/viewarticle/56676/
      Calling Project Items From Scripts/viewarticle/56558/
      TestComplete Helper Objects/viewarticle/56855/
      Handling Exceptions in Scripts/viewarticle/56480/
      Sending E-Mail From Scripts/viewarticle/56308/
      To Do Comments Format and Syntax/viewarticle/57706/
      Using Dictionary Object To Address Array Elements With String Indexes/viewarticle/58138/
      Using Namespaces/viewarticle/55020/
      Using Regular Expressions in Scripts/viewarticle/56414/
      Using Structures in Scripts/viewarticle/56861/
      Using Timers/viewarticle/55006/
      Working With COM Objects/viewarticle/56228/
      Working With COM Ports From Scripts/viewarticle/58080/
      Converting Scripts From One Scripting Language To Another/viewarticle/58076/
     [Collapse]Working With Strings/viewarticle/58075/
       VBScript - Working With Strings/viewarticle/58115/
       JScript - Working With Strings/viewarticle/58113/
       DelphiScript - Working With Strings/viewarticle/58116/
       C++Script, C#Script - Working With Strings/viewarticle/58114/
     [Expand]Working With Time/viewarticle/58078/
     [Expand]Working With Dates/viewarticle/58079/
     [Expand]Working With Numeric Values/viewarticle/58074/
      Working With WMI Objects in Scripts/viewarticle/58097/
    [Expand]Using Code Editor/viewarticle/55044/
    [Expand]Using Code Explorer/viewarticle/62615/
   [Expand]Test Visualizer/viewarticle/55007/
   [Expand]Exploring Applications/viewarticle/55055/
   [Expand]Debugging Tests/viewarticle/56567/
  [Expand]Test Results/viewarticle/55010/
  [Expand]Enhancing Tests/viewarticle/56964/
  [Expand]Teamwork and Integration Into QA Process/viewarticle/57266/
  [Expand]Extending TestComplete/viewarticle/57655/
  [Expand]Automating TestComplete/viewarticle/57438/
  [Expand]Best Practices/viewarticle/64008/
 [Expand]Testing Types/viewarticle/62721/
 [Expand]Applications Testing/viewarticle/62606/
 [Expand]Working With Application Objects and Controls/viewarticle/55815/
 [Expand]Samples and Tutorials/viewarticle/56239/
 [Expand]References/viewarticle/57878/
 [Expand]Other Tools That Help You Test Better/viewarticle/63442/
 [Expand]TestComplete 10 Licensing Guide/viewarticle/63451/
Updated: 7/16/2014 Applies To: TestComplete 10 Rating: AverageAverageAverageAverageAverage 4 vote(s) Click to rate: PoorNot badAverageGoodExcellent
Scripting

VBScript - Working With Strings

This topic contains information about handling strings in VBScript and provides examples of operations that deal with strings. It contains the following sections:

Basics

A String is a sequence of symbols or digits. Strings are among the most frequently used data types. Like any other data type, strings in TestComplete are represented as OLE-compatible variants. In VBScript, a sequence of literal characters, enclosed in double quotes ("), is recognized as a string. Single quotation marks (') are allowed within a string. To insert a double quotation mark into a string, it should be duplicated. The following is an example of string:

VBScript

str1 = "The brig was heading to Liverpool, when the captain noticed a ship."
str2 = "'Ahoy! Is there anyone?' - the captain cried."
str3 = """Nobody."" - was the answer."

To work with strings, TestComplete has a special scripting object - aqString. The object is available for all supported scripting languages, so you can use it to work with string values regardless of the chosen language.

Method, Property Description
aqString.AddListItem Adds a new item to a string list.
aqString.ChangeListItem Changes the value of the string list item with the given index.
aqString.Compare Compares two specified strings.
aqString.Concat Concatenates two specified strings.
aqString.DeleteListItem Removes an item with the given index from a string list.
aqString.Find Searches for a substring within the given string. Use this method instead of the obsolete aqString.Contains.
aqString.Format Generates a formatted string.
aqString.GetChar Retrieves a single character from the input string.
aqString.GetLength Returns the number of characters in a string.
aqString.GetListItem Returns an individual item from the list passed through the input string.
aqString.GetListLength Returns the number of items in the string list.
aqString.Insert Inserts one string to another at the specified position.
aqString.ListSeparator Specifies a character used to separate individual values in a list.
aqString.Quote Encloses the specified string in quotes.
aqString.QuoteSymbol Specifies a symbol used as a quotation mark.
aqString.Remove Removes a number of characters from the input string.
aqString.Replace Replaces all the occurrences of one substring with another substring.
aqString.SubString Retrieves a substring from the input string.
aqString.ToLower Converts the specified string to lower case.
aqString.ToUpper Converts the specified string to upper case.
aqString.Trim Removes spaces and control characters from the specified string.
aqString.Unquote Converts a quoted string to an unquoted string.

Another scripting object that can be used to work with strings is aqConvert. This object has several methods that convert values of different types to a string and vice versa.

Method Description
aqConvert.CurrencyToFormatStr Converts a currency value to a string using the specified format settings.
aqConvert.CurrencyToStr Converts a currency value to a string.
aqConvert.DateTimeToFormatStr Converts the given date value to a string using the specified format.
aqConvert.DateTimeToStr Converts the given date value to a string.
aqConvert.FloatToStr Converts a floating-point value to a string.
aqConvert.IntToStr Converts the given number into a string.
aqConvert.StrToCurrency Converts the specified string to a currency value.
aqConvert.StrToDate Converts the specified string to a date value.
aqConvert.StrToDateTime Converts the specified string to a date/time value.
aqConvert.StrToFloat Converts the specified string to a floating-point value.
aqConvert.StrToInt Converts the specified string to an integer value.
aqConvert.StrToInt64 Converts the specified string to a long integer value.
aqConvert.StrToTime Converts the specified string to a time value.
aqConvert.VarToStr Converts the specified variant value to a string.

Furthermore, you can use native VBScript functions that operate with strings. A detailed description of VBScript functions can be found in the Functions (VBScript) article of the MSDN library. The table below only lists major functions:

Function Description
Asc(string) Returns the ASCII character code corresponding to the first letter in a string.
Chr(charcode) Returns the character associated with the specified ANSI character code.
CStr(expression) Returns an expression that has been converted to a variant of sub-type string.
Escape(charString) Encodes a string so it only contains ASCII characters. Non-ASCII characters are replaced with %xx encoding, where xx is equivalent to the hexadecimal number representing the character.
InStr([startpos, ]string1, string2[, compare]) Returns the position of the first occurrence for one string within another.The search can start at a given position and use binary (compare=0) or text (compare=1) comparisons.
InStrRev(string1, string2[, start[, compare]]) Returns the position of an occurrence for one string within another, from the end of string. The search can start at a given position and use binary (compare=0) or text (compare=1) comparisons.
Join(list[, delimiter]) Returns a string created by joining a number of substrings contained in an array.
LCase(string) Returns a string that has been converted to lowercase.
Left(string, length) Returns a specified number of characters from the left side of a string.
Len(string | varname) Returns the number of characters in a string or the number of bytes required to store a variable.
LTrim(string) Returns a copy of a string without leading spaces.
Mid(string, start[, length]) Returns a specified number of characters from a string.
Replace(string, findstr, replacewith[, start[, count[, compare]]]) Returns a string in which a specified substring has been replaced with another substring a specified number of times.
Right(string, length) Returns a specified number of characters from the right side of a string.
RTrim(string) Returns a copy of a string without trailing spaces.
Space(number) Returns a string consisting of the specified number of spaces.
Split(expression[, delimiter[, count[, compare]]]) Returns a zero-based, one-dimensional array containing a specified number of substrings.
StrComp(string1, string2[, compare]) Returns a value indicating the result of a string comparison.
String(number, character) Returns a repeating character string of the length specified.
StrReverse(string) Returns a string in which the character order of a specified string is reversed.
Trim(string) Returns a copy of a string without leading and trailing spaces.
UCase(string) Returns a string that has been converted to uppercase.
Unescape(charString) Decodes a string encoded with the Escape function.

Special characters

In VBScript you can emulate any character by using the Chr function with the appropriate ASCII code. This also applies to special characters that are used to format string values. Alternatively, you can emulate control characters using native string constants. The table below lists the most frequently used special characters and their constants.

Description Character sequence
Carriage return. Chr(13) -- or -- vbCr
Line feed.
On Unix platforms it is interpreted as new line.
Chr(10) -- or -- vbLf
A combination of carriage return and line feed.
On Windows platforms it is interpreted as new line.
Chr(13)+Chr(10) -- or -- VbCrLf
New line.
Either a line feed character or a combination of carriage return and line feed.
vbNewLine
Form feed. Chr(12) -- or -- vbFormFeed
Horizontal tab. Chr(9) -- or -- vbTab
Vertical tab. Chr(11) -- or -- vbVerticalTab

Special characters obtained by a function or constant should be joined to the string by concatenation:

VBScript

Str1 = "A string." & Chr(13) & Chr(10) & "Another string."
Str2 = "A string." & vbNewLine & "Another string."

Getting the string length

To obtain the total number of characters in a string, you can call either the aqString.GetLength method, or the Len function of VBScript. The character position in VBScript is not zero-based, so the maximum position number in a string equals the string length. The following code demonstrates both ways of obtaining the string length:

VBScript

Sub StringLengthDemo
  Dim aString
  aString="Some text"
  Log.Message("The string is " & aqString.GetLength(aString) & " character(s) long.")
  Log.Message("The string is " & Len(aString) & " character(s) long.")
End Sub

Using TestComplete, you can limit the length of string parameters returned by functions of the tested application. For this purpose, use the Maximum string length of [out] parameters project property. If the length of the string returned from the application via one of its out parameters exceeds the property’s value, TestComplete treats the returned string as a null one.

Concatenating strings

The operation that forms a string out of several others is called concatenation. The aqString object has special method aqString.Concat that perform this operation. In VBScript the concatenation is performed both by plus (+) and by ampersand (&) operators. The plus operator is intended to perform addition, but if both operators are strings, then string concatenation occurs. However it is more convenient to use the ampersand operator since it does not require a preliminary conversion to a string type.

This sample code shows how to make a string out of several substrings:

VBScript

Sub ConcatenationDemo
  Dim Str1
  Str1 = "String No 1 "
  Log.Message(aqString.Concat(Str1, "String No 2"))
  Log.Message(Str1 + "String No 2 " + "String No " + aqConvert.IntToStr(3))
  Log.Message(Str1 & "String No 2 " & "String No " & 3)
End Sub

Comparing strings

String comparison is widely used during testing. Generally, a test procedure obtains textual data (user input, file contents, property values and so on) and then compares it with the expected data. That is why both TestComplete and VBScript have their own methods to compare one string value with another. These methods are: aqString.Compare and StrComp.

The aqString.Compare method has three parameters: two of them, String 1 and String2, specify the strings to be compared; the third parameter (CaseSensitive) defines whether the comparison should be case-sensitive or not.

Similarly, VBScript's StrComp function has two mandatory parameters, Str1 and Str2, that define the compared strings, and one optional parameter, CompType, that specifies the comparison type. The CompType parameter can accept the following values: vbBinaryCompare (or 0), and vbTextCompare (or 1). vbBinaryCompare means binary case-sensitive comparison. vbTextCompare means case-insensitive comparison. The default type is vbBinaryCompare. The function result is -1 if Str1 is less than Str2, 1 if Str1 is greater than Str2 and they equal 0 if the strings are the same.

Both methods can compare strings holding specific national symbols, for example characters with diacritical marks ( , , and others).

The code below demonstrates how to use both methods:

VBScript

' This helper function obtains the integer comparison result from the
' StrComp routine and returns a textual interpretation of the result.
Function GetComparisonStr(IntegerComparisonResult)
  If IntegerComparisonResult = 0 Then
        GetComparisonStr = CStr(IntegerComparisonResult) & ". The strings are the same."
      Else
        GetComparisonStr = CStr(IntegerComparisonResult) & ". The strings are different."
  End If
End Function

Sub StringComparison
  ' Use the method of the aqString object
  Log.Message("aqString.Compare(""Abra"", ""abra"", False): " & aqString.Compare("Abra", "abra", False))
  Log.Message("aqString.Compare(""Abra"", ""abra"", True): "& aqString.Compare("Abra", "abra", True))

  ' Use the native routine of VBScript
  Log.Message("StrComp(""abra"", ""ABRA"", vbBinaryCompare): " & GetComparisonStr(StrComp("abra", "ABRA", vbBinaryCompare)))
  Log.Message("StrComp(""abra"", ""ABRA"", vbTextCompare): " & GetComparisonStr(StrComp("abra", "ABRA", vbTextCompare)))

  ' Working with native-language characters
  ' The following code assumes that the French layout is installed on the computer
  ' 040C is the identifier of the French layout
  If IsLanguageSupported(&H040C) And SetKeyboardLayout(Sys.Process("TestComplete").Id, &H040C) Then
    Log.Message("aqString.Compare(""français"", ""Français"", False): " & aqString.Compare("français","Français", True))
    Log.Message("aqString.Compare(""français"", ""Français"", True): " & aqString.Compare("français","Français", False))
    Log.Message("aqString.Compare(""français"", ""francais"", True): " & aqString.Compare("français","francais", False))

    Log.Message("StrComp(""français"", ""Français"", vbBinaryCompare): " & GetComparisonStr(StrComp("français", "Français", vbBinaryCompare)))
    Log.Message("StrComp(""français"", ""Français"", vbTextCompare): " & GetComparisonStr(StrComp("français", "Français", vbTextCompare)))
    Log.Message("StrComp(""français"", ""francais"", vbTextCompare): " & GetComparisonStr(StrComp("français", "francais", vbTextCompare)))
  End If
End Sub

Accessing individual character of a string

The VBScript scripting language has no data type that can be used to store single symbols. However, this is not a problem, since the string type can hold both a series of characters and individual characters. Moreover, you can extract a single character from a string using the aqString.GetChar method and VBScript’s Mid function. The latter retrieves the given number of characters starting from the specified position. Note however that the VBScript function uses 1-based indexes, whereas the GetChar method uses zero-based indexes. The sample routine below demonstrates how to use both of these routines. It posts text to TestComplete’s log in two different ways: as a whole string and by a single letter.

VBScript

Sub StringByLetter
  Dim aString, i
  aString = "Per aspera ad astra"
  Log.Message("The string is : " & aString)
  Log.Message("And now this text letter by letter using aqString.GetChar:")
  For i = 0 To aqString.GetLength(aString)-1
    Log.Message(aqString.GetChar(aString, i))
  Next
  Log.Message("And now this text letter by letter using Mid function:")
  For i = 1 To Len(aString)
    Log.Message(Mid(aString, i, 1))
  Next
End Sub

Searching for characters and substrings

One of the most common tasks that one has to perform when working with string values is determining whether specific text is part of a string. To perform such tasks, the aqString object has the Find method. If the specified substring was found, the method returns the number of the first occurrence of the substring within the source string. If the specified substring was not found, the method returns -1:

VBScript

Sub StringOccurrenceDemo
  Dim aString, aSubString, Res

  aString = "Per aspera ad astra"
  aSubString = "astra"
  Res = aqString.Find(aString, aSubString)
  If Res <> -1 Then
    Log.Message("A substring '" & aSubString & "' was found in string '" & aString & "' at position " & Res)
  Else
    Log.Message("There are no occurrences of '" & aSubString & "' in '" & aString & "'")
  End If
End Sub

You can also get the position where the specified substring occurs using the VBScript functions InStr and InStrRev. They both return the initial position (from 1) of the first substring match, but the first one searches from left to right, while the other from right to left. If the substring was found, the functions return the initial position of the first substring match. If no occurrences were found, they return 0. The code below demonstrates how to use the InStr function:

VBScript

Sub TextPosDemo
  Dim aString, aSubString, findpos

  aString = "Per aspera ad astra"
  aSubString = "astra"
  findpos = InStr(aString, aSubString)
  If findpos <> 0 Then
    Log.Message("A substring '" & aSubString & "' was found at position " & findpos)
  Else
    Log.Message("There are no occurrences of '" & aSubString & "' in '" & aString & "'")
  End If
End Sub

Getting a substring

VBScript has several methods that allow you to extract a substring out of a string. They are Left, Right and Mid. These methods vary in how the extracted substring is defined.

Function Left returns a text fragment that starts at the beginning of the given string and has the specified length. Function Right does a similar action, but it gets the last fragment of the given string. If the fragment’s length is greater than the length of the whole string, then the entire string is returned. Negative length values are not allowed, zero-length returns an empty string.

Function Mid returns a text fragment that starts at a given position and has a specified length. The length parameter is optional, and if it is omitted then the resulting substring continues up to the end of the source string.

The aqString object also has a similar method, SubString that returns a substring that starts from the specified position and has the given length. However, this method requires all tree parameters, and position numbers are zero-based.

The sample code below demonstrates how to use these functions:

VBScript

Sub GetStringDemo
  Dim Str
  Str = "123456789"

  Log.Message("Function 'Left' demo:")
  Log.Message(Left(Str, 3)) ' Posts "123"
  Log.Message(Left(Str, 20)) ' Posts "123456789"
  Log.Message(Left(Str, 0)) ' Posts ""

  Log.Message("Function 'Right' demo:")
  Log.Message(Right(Str, 3)) ' Posts "789"
  Log.Message(Right(Str, 20)) ' Posts "123456789"
  Log.Message(Right(Str, 0)) ' Posts ""

  Log.Message("Function 'Mid' demo:")
  Log.Message(Mid(Str, 4, 3)) ' Posts "456"
  Log.Message(Mid(Str, 5)) ' Posts "456789"
  Log.Message(Mid(Str, 4, 0)) ' Posts ""

  Log.Message("Method 'aqString.SubString' demo:")
  Log.Message(aqString.SubString(Str, 3, 3)) ' Posts "456"
  Log.Message(aqString.SubString(Str, 4, 20)) ' Posts "56789"
  Log.Message(aqString.SubString(Str, 2, 0)) ' Posts ""
End Sub

Splitting strings

Sometimes it is required to make several strings out of a single string. This operation splits a string into substrings. It can be performed by VBScript's native function called Split. This routine searches the string for a delimiter character, separates the string and returns an array holding the constituent strings. If the delimiter is omitted, then the space character is assumed as a delimiter. Also you can constrain the maximum array length with the third parameter and set the comparison method with the forth. They are not obligatory and can be omitted. The same method can be used to split a string onto substrings, sentences and even separate words; it all depends on the specified delimiter. The first sample routine below uses a space character as a delimiter to extract words out of a string, and the second routine splits the string by line breaks:

VBScript

Sub SplitDemo
    Dim s, ss

    s = "Better late than never but better never late."
    ' Split at each space character.
    ss = Split(s)
    Log.Message("There are " & (UBound(ss)+1) & " words in the array")
    Log.Message("The first word is: " & ss(0))
End Sub


Sub SplitDemo2
    Dim s, ss

    s = "Better late than never " & Chr(13) & " but better never late."
    ' Split at line break character.
    ss = Split(s, Chr(13))
    Log.Message("There are " & (UBound(ss)+1) & " words in the array")
    Log.Message("The first word is: " & ss(0))
End Sub

TestComplete has a similar method called aqString.GetListItem. It extracts a substring with the specified index from the input string. It was designed to read items from a string list, see Working with string lists for more information. However, it allows you to redefine the delimiter characters and, like the Split method, it can be used to get sentences, single words and so on.

VBScript

Sub SplitDemo3
    Dim s, prevSep

    s = "Better late than never but better never late."
    ' Assign list separator to space character
    prevSep = aqString.ListSeparator
    aqString.ListSeparator = " "
    ' Split by spaces
    Log.Message("There are " & aqString.GetListLength(s) & " words in a string")
    Log.Message("The first word is: " & aqString.GetListItem(s, 0))
    ' Restore previous separator
    aqString.ListSeparator = prevSep
End Sub

Removing extra spaces from a string

The aqString object has a special routine, aqString.Trim, that excludes leading and trailing spaces (or both) from a string. VBScript has also the LTrim, RTrim and Trim functions that exclude, leading, trailing and both leading and trailing spaces from the input string. Generally, all these methods are used to remove unnecessary spaces at the beginning or at the end of strings obtained from the user input.

VBScript

Sub TrimDemo
  Dim str
  str="  Hallo  "

  Log.Message("'" & aqString.Trim(str, aqString.stLeading) & "'") 'Posts 'Hallo  '
  Log.Message("'" & aqString.Trim(str, aqString.stTrailing) & "'") 'Posts '  Hallo'
  Log.Message("'" & aqString.Trim(str, aqString.stAll) & "'") 'Posts 'Hallo'

  Log.Message("'" & LTrim(str) & "'") ' Posts 'Hallo  '
  Log.Message("'" & RTrim(str) & "'") ' Posts '  Hallo'
  Log.Message("'" & Trim(str) & "'") ' Posts 'Hallo'
End Sub

Another function that can be useful when handling user input strings is excluding extra inner spaces out of the string. This function seems to be similar to Trim, but the latter only removes spaces at the beginning or end of the string and does not affect the spaces inside the string. The general idea of the function is for the string to be parsed into separate words and then a new string is constructed. The new string consists of the same words but is separated with a single space between words.

VBScript

Function TrimInner(Str)
    Dim WordArray, i
    WordArray = Split(Str)
    Str = ""
    For i = 0 To UBound(WordArray)
      If WordArray(i) <> "" Then Str = Str & WordArray(i) & " "
    Next
    TrimInner = Trim(Str)
End Function


'An example of how to use this function
Sub TrimInnerDemo
  Log.Message(TrimInner("Follow the     white rabbit"))
End Sub

Replacing characters and substrings

Quite often we need to find and replace a character or substring within a string. There are two ways to do this: by using the aqString.Replace method or by using the Replace method of a RegExp object.

The aqString object method is much easier to use. It can be used when you need to change a certain character or string. It allows you to set whether the search should be case-sensitive or not. Here is an example of how to use this method:

VBScript

Sub StringReplaceDemo
  Dim str
  str = "Hi, Bob. Have you seen Bob Robbinson?"

  str = aqString.Replace(str, "Bob", "Jack")
  Log.Message(str)
End Sub

The RegExp.Replace method is a little more complicated, but it offers more flexibility. You can not only change a definite character or string, but all fragments matching the specified regular expression pattern. However you have to create an instance of the RegExp object and set the pattern before replacing. The regular expression pattern is enclosed in double quotation marks ("). Additionally you can specify the following Boolean flags that affect the search procedure: RegExp.Global - performs a global search for all occurrences of a pattern, RegExp.IgnoreCase - searches regardless of the letter case and RegExp.MultiLine - performs a multi-line search. For a full description of how to use regular expressions, refer to the Introduction to Regular Expressions article in the MSDN library.

The first sample demonstrates how to change a definite string using the replace method.

VBScript

Sub RegExReplaceDemo1
  Dim str, re
  str = "Hi, Bob. Have you seen Bob Robbinson?"
  ' Create RegExp instance.
  Set re = New RegExp
  ' Define regular expression pattern
  re.Pattern = "Bob"
  ' Set global search flag
  re.Global = True
  ' Perform replace operation
  str = re.Replace(str, "Jack")
  Log.Message(str)
End Sub

The second example shows how to replace a substring with alternative parts. The patterns of alternative parts are separated by pipe characters (" | "). For instance in the sample below the "ht(ml|m)" pattern matches both html and htm:

VBScript

Sub RegExReplaceDemo2
  Dim str, re
  str = "The html is widely used in Internet. The HTM file is a text file with tags."
  ' Create RegExp instance.
  Set re = New RegExp
  ' Define regular expression pattern.
  re.Pattern = "ht(ml|m)"
  ' Set global search flag
  re.Global = True
  ' Set ignore letter case flag
  re.IgnoreCase = True
  ' Perform replace operation
  str = re.Replace(str, "hypertext markup language")
  Log.Message(str)
End Sub

Furthermore, using regular expressions you can search for the text fragments that match the specified format. In the next sample, all dates written in the DD/MM/YYYY format are substituted with the Some Date string. This operation can be useful, for example, when comparing two reports that contain the generation date.

VBScript

Sub RegExReplaceDemo3
  Dim str, re
  str = "Date of report: 30/04/2005."
  ' Create RegExp instance.
  Set re = New RegExp
  ' Define regular expression pattern.
  re.Pattern = "\d{1,2}.\d{1,2}.\d{2,4}"
  ' Set global search flag
  re.Global = True
  ' Perform replace operation
  str = re.Replace(str, "Some Date")
  Log.Message(str)
End Sub

Changing the letter case

A string can contain both uppercase and lowercase letters. TestComplete's aqString object and the native String object have methods that convert uppercase letters to lowercase and vice versa. They are: aqString.ToLower, aqString.ToUpper, LCase and UCase.

The code below demonstrates how all of these methods are applied.

VBScript

Sub LetterCaseDemo
  Dim str
  str = "The word 'Champagne' is of French origin"

  ' Converting to lower case
  Log.Message(aqString.ToLower(str))
  Log.Message(LCase(str))

  ' Converting to upper case
  Log.Message(aqString.ToUpper(str))
  Log.Message(UCase(str))
End Sub

Working with string lists

Some scripting objects, generally, controls like ListBoxes, ComboBoxes and Memos, return information about their state or contents as string lists. Individual data elements (or items) in this list are separated by commas, line breaks, carriage returns or some other delimiter characters.

The aqString object has a number of specific methods (AddListItem, ChangeListItem, DeleteListItem, GetListItem and GetListLength) that are used to work with such lists. AddListItem and DeleteListItem add an item to or remove if from the list respectively. The GetListItem method retrieves the item with the given index, and ChangeListItem assigns a new value to the given item. The GetListLength method returns the total number of items in the string list.

The symbol that is used as the separator between list items is defined by the ListSeparator property. By default, the list separator is a pipe (|), but it can also be a comma, column, line break, carriage return, tabulation, and any other printable and non-printable character, or even several characters.

Here is sample code that demonstrates how to work with the string lists returned by scripting objects.

VBScript

Sub ListDialogOptions
    Dim StrList, prevSep, i

    ' Get a string with dialog options
    OptStr = UserForms.UserForm1.SaveDialog1.Options
    ' Assign a comma as the list separator
    prevSep = aqString.ListSeparator
    aqString.ListSeparator = ","
    ' Get the number of dialog options
    Log.Message("The dialog has " & aqString.GetListLength(OptStr) & " option(s) enabled:")
    ' Iterate through the options list
    For i = 0 To aqString.GetListLength(OptStr)-1
      ' Get an option and post it to the log
      Log.Message("Option No " & (i+1) & " is: " & aqString.GetListItem(OptStr, i))
      Next
    ' Restore the previous separator
    aqString.ListSeparator = prevSep
End Sub

Sub ManageMemoText
    Dim StrList, prevSep

    ' Get a string with memo lines
    StrList = UserForms.UserForm1.cxMemo1.Lines.Text
    ' Post the memo contents to the log
    Log.Message(UserForms.UserForm1.cxMemo1.Lines.Text)
    ' Assign a newline character as the list separator
    prevSep = aqString.ListSeparator
    aqString.ListSeparator = vbNewLine
    ' Append one more line
    StrList = aqString.AddListItem(StrList, "Last Line")
    Log.Message(StrList)
    ' Change the value of the first line
    StrList = aqString.ChangeListItem(StrList, "New First Line", 0)
    ' Add the memo contents to a new list
    UserForms.UserForm1.cxMemo1.Lines.Text = StrList
    ' Post the memo contents to the log
    Log.Message(UserForms.UserForm1.cxMemo1.Lines.Text)
    ' Restore the previous separator
    aqString.ListSeparator = prevSep
End Sub

See also
Working With Strings | aqString Object | aqConvert Object


© 2014 SmartBear Software. All rights reserved.
Email Send feedback on this document