Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Showing posts with label Programming in VbScript. Show all posts
Showing posts with label Programming in VbScript. Show all posts

Regular Expression In QTP

How to Use regular Expression in QTP programming

Here our objective is to figure out the frequency of occurance of any string.

Set re = New RegExp
re.Global = True
re.Pattern = "Viplav"
s = "Viplav is a wonderful guy and has all the more Viplav in him, I have not come acros  any other Viplav like human in my whole Viplav"
Set strMatch = re.Execute(s)
MsgBox strMatch.count

For gaining more insights in the automation using QTP log on to below url :

Automation Testing Using QTP

Vbscript Coding In QTP

Vbscript Coding In QTP


In the below article we will discuss the following topics related to the VBScripting in QTP.
  1. While .. Wend Looping In QTP.
  2. For ...Loop Handling In QTP VBScript.
  3. If ...End If Handling in VBScript in QTP.
  4. Usage of For...Each Loop in QTP Vbscripting.
  5. ChildObjects in QTP.
  6. LoadAndRunAction method.
  7. ReDimUsage in Vbscripting QTP.
  8. SystemUtil Usage in VbScripting  QTP.
  9. ExecQuery
  10. IE.Terminate()
  11. Associated library :
  12. Action Code :
  13. The LoadAndRunAction method allows calling any Action for Local system or Quality center at run-time.


Regular Expression in VBScript in QTP :
 
Dim text
text = ""

Dim rgx
Set rgx = New RegExp
rgx.IgnoreCase = True
rgx.Global = True
rgx.Pattern = "([A-Za-z]{3,9})://([-;:&=\+\$,\w]+@{1})?([-A-Za-z0-9\.]+)+:?(\d+)?((/[-\+~%/\.\w]+)?\??([-\+=&;%@\.\w]+)?#?([\w]+)?)?"

Dim match, matches
Set matches = rgx.Execute(text)
For Each match in matches
  MsgBox match.Value, 0, "Found Match"
Next

'Launch a notepad window :
 
SystemUtil.Run "notepad.exe"
 
'Close the window just launched using the exact title :

SystemUtil.CloseProcessByWndTitle "Untitled - Notepad"
 
'Launch a notepad window
SystemUtil.Run "notepad.exe"
 
'Close the window just launched using a pattern string
SystemUtil.CloseProcessByWndTitle ".*Notepad", True
 
SystemUtil.CloseDescendentProcesses
 
CloseDescendentProcesses can be used to close any process launched by QTP. The code below illustrates the usage
 
'Launch explorer
SystemUtil.Run "iexplore.exe"
 
'Launch excel using COM
Set oXL = CreateObject("Excel.Application")
oXL.Visible = True
 
'Close processes launched by QTP. This will close
'the internet explorer and Excel as well
SystemUtil.CloseDescendentProcesses

While Browser("creationtime:=0").Exist(0)
 
    'Close the browser
    Browser("creationtime:=0").Close
 
Wend

'Create a description for browser
Set oBrowser = Description.Create
oBrowser("micclass").Value = "Browser"
 
Set oPage = Description.Create
oPage("micclass").Value = "Page"
 
'Get all browsers
Set allBrowser = Desktop.ChildObjects(oBrowser)
 
Dim i, iCount
 
iCount = allBrowser.Count - 1
 
For i = 0 To iCount
    'Get the page object from the browser
    Set oPg = allBrowser(i).ChildObjects(oPage)(0)
 
    'Get the URL of the
    If InStr(oPg.GetROProperty("title"), "Quality Center", vbTextCompare) = 0 Then
        'Close the browser
        allBrowser(i).Close
    End If
Next
 
By now you must be wondering about the line
 
'Get the page object from the browser
Set oPg = allBrowser(i).ChildObjects(oPage)(0)

'Name/IP of the computer
sComp = "."
 
'Get the WMI object
Set WMI = GetObject("winmgmts:\\" & sComp & "\root\cimv2")
 
'Get collection of processes for with name iexplore.exe
Set allIE = WMI.ExecQuery("Select * from Win32_Process Where Name = 'iexplore.exe'")
 
'Loop through each process and terminate it
For Each IE in allIE
    IE.Terminate()
Next

'Create the shell application object
Set shlApp = CreateObject("Shell.Application")
 
'Get all open windows collection
Set allWins = shlApp.Windows
 
'Loop through each window and close if IE
For Each window In allWins
    If InStr(window.fullName, "iexplore.exe") Then
        'Close the IE window
        window.Quit
    End If
Next

Dim windows2Close
 
'Initialize with negative upper bound
ReDim windows2Close( -1)
 
'Create the shell application object
Set shlApp = CreateObject("Shell.Application")
 
'Get all open windows collection
Set allWins = shlApp.Windows
 
'Loop through each window and close if IE
For Each window In allWins
    'Close all IE windows but ignore Quality Center
    If InStr(window.fullName, "iexplore.exe") And InStr(Window.LocationURL, "/qcbin/") = 0 Then
 
        'Increase the array size by 1
        ReDim Preserve windows2Close(UBound(windows2Close) + 1)
 
        Set windows2Close(UBound(windows2Close)) = Window
    End If
Next
 
'Loop through all array elements and close each window
For Each Window In windows2Close
    Window.Quit
Next
WebUtil.DeleteCookies()
Function DeleteIECookies()
    Set oWebUtil = CreateObject("Mercury.GUI_WebUtil")
    oWebUtil.DeleteCookies()
End Function
Function DeleteFFCookies()
    Dim FSO, cookiePath
    Set FSO = CreateObject("Scripting.FileSystemObject")
 
    cookiePath = GetFFCookiesPath()
 
    If FSO.FileExists(cookiePath) Then FSO.DeleteFile cookiePath
 
End Function
Function GetFFCookiesPath()
                    Dim FSO, oShell
                    Set FSO = CreateObject("Scripting.FileSystemObject")
                    Set oShell = CreateObject("WScript.Shell")
 
                    If InStr(Environment("OS"),"Vista") Then
                                         Dim sUserProf
                                         sUserProf = oShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\AppData\Roaming\Mozilla\Firefox\Profiles"
                                         GetFFCookiesPath = ""
 
                                         If FSO.FolderExists(sUserProf)  Then
                                           Set oFolder =  FSO.GetFolder(sUserProf)
                                           If oFolder.SubFolders.Count> 0 Then
 
                                                             'oFolder.item(0) throws an error, so we use a workaround to find the first folder                
                                                             For each oFolder in oFolder.SubFolders
                                                                                 Exit For
                                                             Next
                                                             'Set oFolder = oFolder.item(0)
                                                             Dim sPath
                                                             sPath = oFolder.Path
 
                                                             If FSO.FileExists(sPath & "\Cookies.txt") Then
                                                               GetFFCookiesPath = sPath & "\Cookies.txt"
                                                             End If
                                           End If
                                         End If
                    Else
                                         Err.raise vbObjectError + 1, "GetFFCookiesPath", "This function has not yet been implemented for your OS - " & Environment("OS") 
                    End if
End Function
Function Login(username, password)
                    oUserTxt.Set username
                    oUserPwd.Set Ucase(password)
                    oLogin.Click
End Function
ExecuteFile PathFinder.Locate("LoginUpdate.vbs")
 
Associated library :

Function NewMsgBox(Message)
                    Print "The user says – " & Message
End Function

Dim fnPtrNewMsgBox
Set fnPtrNewMsgBox = GetRef("NewMsgBox")

Action Code :

Dim MsgBox

Set MsgBox = fnPtrNewMsgBox

Msgbox "Tarun"

The advantage of this approach is that we can use the original MsgBox function as well in the NewMsgBox method which was not possible with the earlier approach
orkaround to that I decided to use a new ActualParams objects. So the Library was updated as
Dim ActualParams

'By default we will use the component parameters
Set ActualParams = Parameter

Function App_Login()
                    Browser("X").Page("X").WebEdit("UserName").Set ActualParams("UserName")
                    Browser("X").Page("X").WebEdit("Password").Set ActualParams("Password")
                    Browser("X").Page("X").WebButton("Login").Click
End Function
Now I can use the function as below in my component
'Call with component parameter
Call App_Login

Dim DummyParams
Set DummyParams = CreateObject("Scripting.Dictionary")
DummyParams("UserName") = "Tarun"
DummyParams("Password") = "Tarun" ' Do remember that password field should be first encrypted

'Set the Actual parameters be used in Function as DummyParams
Set ActualParams = DummyParams
Call App_Login

'Rest of the functions to use the component parameters
Set ActualParams = Parameter

The LoadAndRunAction method allows calling any Action for Local system or Quality center at run-time.

LoadAndRunAction(TestPath, ActionName, [Iteration], [Parameters])
'Get the Test type
TestType = DataTable.Value("TestType",dtGlobalSheet)

'Load and call the Action
LoadAndRunAction "C:\Framework\Tests\Actions", TestType

Find a given value in a property of the collection of child objects In QTP

Activate an Edit Box's Native Focus Method  :

Sub Object_Example()
'The following example uses the .Object property to activate an
'edit box's native focus method:

Set MyWebEdit = Browser("Mercury Tours").Page("Mercury Tours").WebEdit("username").Object
MyWebEdit.focus

End Sub


 Find a given value in a property of the collection of child objects:

Sub ROPropertyOfChildObjects()

' Find a given value in a property of the collection of child objects
Dim lvToSearch, ValueToSelect, NumberOfListViews, ListViewCollection

'Search for this value of the 'swfname" property for the SwfListView.
lvToSearch = "listView" ' "files"
ValueToSelect = "Invoice 2345"
'Create a description object to retrieve all WebEdits in a specific page.
Set oDesc = Description.Create()
oDesc("swftypename").Value = "System.Windows.Forms.ListView"
'Retrieve all The ListView objects in this window
Set ListViewCollection = SwfWindow("dotNET ListView").ChildObjects(oDesc)
NumberOfListViews = ListViewCollection.Count
' Select the first matching item in the WListView
For i = 0 To NumberOfListViews - 1
    If ListViewCollection(i).GetROProperty("swfname") = lvToSearch Then
        ListViewCollection(i).Select ValueToSelect
        Exit For
    End If
Next
' Do something with the selected item
End Sub


Get a Property from a Button  :


Sub GetROProperty_Example()
'The following example uses the GetROProperty method to retrieve the value of the text property for the
'"button4" button.
strText = SwfWindow("Form1").SwfButton("button4").GetROProperty("Text")

End Sub
 
Retrieve a Calendar's Selection Mode Property :


Sub GetROProperty_Example()
'The following example uses the GetROProperty method to retrieve the value of the selection mode
'property for the "Calendar1" calendar.
runtimeProp = Browser("Browser").Page("Page").WbfCalendar("Calendar1").GetROProperty("selection mode")

End Sub



Finding y Co ordinate of an Object :

Sub GetROProperty_Example()
'The following example uses the GetROProperty method to retrieve the
'Y coordinate of the AcxCheckBox object relative to the top left
'corner of the screen.

Set Value = Browser("Flight").Page("Flight").AcxCheckBox("LogicalName").GetROProperty("abs_y")

End Sub

Object Identification by Descriptive Programming

Descriptive Programming Using VbScript

Find All List Objects On a Web Page :


Sub ChildObjects_Example()
'The following example uses the ChildObjects method to find all the
'list objects on a Web page, and then to select an item in each list.

Set oDesc = Description.Create()
    oDesc("micclass").Value = "WebList"
Set Lists = Browser("Mercury Interactive").Page("Mercury Interactive").ChildObjects(oDesc)
    NumberOfLists = Lists.Count()
For i = 0 To NumberOfLists - 1
    Lists(i).Select i + 1
Next

End Sub



Find All Web Edit Objects On a Web Page :


Sub ChildObjects_Example()

'The following example retrieves the collection of
'WebEdit objects in order to find a specific
'WebEdit object in a page and set a value for it.

Dim EditToSearch, ValueToSet, NumberOfEdits

'This is the value of the 'name' property for the WebEdit object we want to find.
EditToSearch = "credit_card_number"

ValueToSet = "3558986773230578"

'Create a description object to help retrieve all WebEdit objects in a specific page.
Set oDesc = Description.Create()
    oDesc("micclass").Value = "WebEdit"
    oDesc("name").Value = "credit_card_number"

'Retrieve all WebEdit objects in this page
Set EditCollection = Browser("Book a Flight: Mercury").Page("Book a Flight: Mercury").ChildObjects(oDesc)

NumberOfEdits = EditCollection.Count

'Search for a specific WebEdit object and set its value
For i = 0 To NumberOfEdits - 1
    If EditCollection(i).GetROProperty("name") = EditToSearch Then
       EditCollection(i).Set ValueToSet
    End If
Next
End Sub



Find All Specific Web Edit Objects On a Web Page :

Sub ChildObjects_Example()

'The following example retrieves the collection of
'WebEdit objects that contain credit card numbers
'and inserts them in an Excel file.

Dim NumberOfEdits

'Create a Description object to help retrieve all
'WebEdit objects in a specific page.
Set oDesc = Description.Create()
    oDesc("micclass").Value = "WebEdit"

'Retrieve all WebEdit objects from this page.
Set EditCollection = Browser("Book a Flight: Mercury").Page("Book a Flight: Mercury").ChildObjects(oDesc)
NumberOfEdits = EditCollection.Count

'Use the GetROProperty to retrieve the "text" property
'(which in this case represents a credit card number),
'and insert all retrieved credit card numbers in an Excel file.
For i = 0 To NumberOfEdits - 1
     CurrentCreditNumber = EditCollection(i).GetROProperty("text")
     WriteToCreditCardNumberExcelFile (CurrentCreditNumber)
Next

End Sub




Retrieve the Value of a Property Using QTP

Retrieve the Current State of a Check Box :


Sub GetROProperty_Example()
'The following example uses the GetROProperty method to retrieve
'the state of a check box.

Val = Browser("Mercury Tours").Page("Find Flights").WebCheckBox("roundtrip").GetROProperty("Value")
' val contains the ON or OFF state of the check box

End Sub


Retrieve the Value of a Property in an Edit Box  :

Sub GetROProperty_Example()

'The following example iterates through the WebEdit objects
'on a page, searching for a specific WebEdit object in order
'to set a value for it.

Dim EditToSearch, ValueToSet, NumberOfEdits

'This is the value of the 'name' property for the WebEdit we want to find.
EditToSearch = "credit_card_number"

ValueToSet = "6543210123456789"
'Create a description object to help retrieve all WebEdit objects in a specific page.
Set oDesc = Description.Create()
oDesc("micclass").Value = "WebEdit"
'Retrieve all WebEdit objects in this page
Set EditCollection = Browser("Book a Flight: Mercury").Page("Book a Flight: Mercury").ChildObjects(oDesc)

NumberOfEdits = EditCollection.Count
'Search for a specific WebEdit and set its value
For i = 0 To NumberOfEdits - 1
    If EditCollection(i).GetROProperty("name") = EditToSearch Then
        EditCollection(i).Set ValueToSet
    End If
Next
End Sub


Retrieve the Value of a Property in an Edit Box :
  
Sub GetROProperty_Example()
'The following example uses the GetROProperty method to retrieve
'the number of items in a WebRadioGroup.

NumOfItems = Browser("Mercury Tours").Page("Find Flights").WebRadioGroup("seat pref").GetROProperty("Items Count")
' NumOfItems contains "3"

End Sub

Coding Conventions In Vbscript Visual Basic

Coding conventions are suggestions are designed to help you write code using Microsoft Visual Basic Scripting Edition. Coding conventions can include the following:
  • Naming conventions for objects, variables, and procedures
  • Commenting conventions
  • Text formatting and indenting guidelines
The main reason for using a consistent set of coding conventions is to standardize the structure and coding style of a script or set of scripts so that you and others can easily read and understand the code. Using good coding conventions results in clear, precise, and readable source code that is consistent with other language conventions and is intuitive.

Constant Naming Conventions

Earlier versions of VBScript had no mechanism for creating user-defined constants. Constants, if used, were implemented as variables and distinguished from other variables using all uppercase characters. Multiple words were separated using the underscore (_) character. For example:
USER_LIST_MAX
NEW_LINE
While this is still an acceptable way to identify your constants, you may want to use an alternative naming scheme, now that you can create true constants using the Const statement. This convention uses a mixed-case format in which constant names have a "con" prefix. For example:
conYourOwnConstant

Variable Naming Conventions

To enhance readability and consistency, use the following prefixes with descriptive names for variables in your VBScript code.
Subtype Prefix Example
Boolean bln blnFound
Byte byt bytRasterData
Date (Time) dtm dtmStart
Double dbl dblTolerance
Error err errOrderNum
Integer int intQuantity
Long lng lngDistance
Object obj objCurrent
Single sng sngAverage
String str strFirstName

Variable Scope

Variables should always be defined with the smallest scope possible. VBScript variables can have the following scope.
Scope Where Variable Is Declared Visibility
Procedure-level Event, Function, or Sub procedure. Visible in the procedure in which it is declared.
Script-level HEAD section of an HTML page, outside any procedure. Visible in every procedure in the script.

Variable Scope Prefixes

As script size grows, so does the value of being able to quickly differentiate the scope of variables. A one-letter scope prefix preceding the type prefix provides this, without unduly increasing the size of variable names.
Scope Prefix Example
Procedure-level None dblVelocity
Script-level s sblnCalcInProgress

Descriptive Variable and Procedure Names

The body of a variable or procedure name should use mixed case and should be as descriptive as necessary. In addition, procedure names should begin with a verb, such as InitNameArray or CloseDialog.
For frequently used or long terms, standard abbreviations are recommended to help keep name length reasonable. In general, variable names greater than 32 characters can be difficult to read. When using abbreviations, make sure they are consistent throughout the entire script. For example, randomly switching between Cnt and Count within a script or set of scripts may lead to confusion.

Object Naming Conventions

The following table lists recommended conventions for objects you may encounter while programming VBScript.
Object type Prefix Example
3D Panel pnl pnlGroup
Animated button ani aniMailBox
Check box chk chkReadOnly
Combo box, drop-down list box cbo cboEnglish
Command button cmd cmdExit
Common dialog dlg dlgFileOpen
Frame fra fraLanguage
Horizontal scroll bar hsb hsbVolume
Image img imgIcon
Label lbl lblHelpMessage
Line lin linVertical
List Box lst lstPolicyCodes
Spin spn spnPages
Text box txt txtLastName
Vertical scroll bar vsb vsbRate
Slider sld sldScale

Code Commenting Conventions

All procedures should begin with a brief comment describing what they do. This description should not describe the implementation details (how it does it) because these often change over time, resulting in unnecessary comment maintenance work, or worse, erroneous comments. The code itself and any necessary inline comments describe the implementation.
Arguments passed to a procedure should be described when their purpose is not obvious and when the procedure expects the arguments to be in a specific range. Return values for functions and variables that are changed by a procedure, especially through reference arguments, should also be described at the beginning of each procedure.
Procedure header comments should include the following section headings. For examples, see the "Formatting Your Code" section that follows.
Section Heading Comment Contents
Purpose What the procedure does (not how).
Assumptions List of any external variable, control, or other element whose state affects this procedure.
Effects List of the procedure's effect on each external variable, control, or other element.
Inputs Explanation of each argument that is not obvious. Each argument should be on a separate line with inline comments.
Return Values Explanation of the value returned.
Remember the following points:
  • Every important variable declaration should include an inline comment describing the use of the variable being declared.
  • Variables, controls, and procedures should be named clearly to ensure that inline comments are only needed for complex implementation details.
  • At the beginning of your script, you should include an overview that describes the script, enumerating objects, procedures, algorithms, dialog boxes, and other system dependencies. Sometimes a piece of pseudocode describing the algorithm can be helpful.

Formatting Your Code

Screen space should be conserved as much as possible, while still allowing code formatting to reflect logic structure and nesting. Here are a few suggestions:
  • Indent standard nested blocks four spaces.
  • Indent the overview comments of a procedure one space.
  • Indent the highest level statements that follow the overview comments four spaces, with each nested block indented an additional four spaces.
The following code adheres to VBScript coding conventions.
'*********************************************************
' Purpose: Locates the first occurrence of a specified user 
'          in the UserList array.
' Inputs: strUserList(): the list of users to be searched.
'         strTargetUser: the name of the user to search for.
' Returns: The index of the first occurrence of the strTargetUser 
'          in the strUserList array. 
'          If the target user is not found, return -1.
'*********************************************************
Function intFindUser (strUserList(), strTargetUser)
    Dim i   ' Loop counter.
    Dim blnFound   ' Target found flag
    intFindUser = -1
    i = 0   ' Initialize loop counter
    Do While i <= Ubound(strUserList) and Not blnFound
      If strUserList(i) = strTargetUser Then 
         blnFound = True   ' Set flag to True
         intFindUser = i   ' Set return value to loop count
      End If
      i = i + 1   ' Increment loop counter
    Loop
End Function

Handling Regular Expression In QTP

What is : A regular expression is a pattern of text that consists of ordinary characters (for example, letters a through z) and special characters, known as metacharacters. The pattern describes one or more strings to match when searching a body of text. The regular expression serves as a template for matching a character pattern to the string being searched.
Here are some examples of regular expression you might encounter:
JScript VBScript Matches
/^\[ \t]*$/ "^\[ \t]*$" Match a blank line.
/\d{2}-\d{5}/ "\d{2}-\d{5}" Validate an ID number consisting of 2 digits, a hyphen, and another 5 digits.
/<(.*)>.*<\/\1>/ "<(.*)>.*<\/\1>" Match an HTML tag.
The following table contains the complete list of metacharacters and their behavior in the context of regular expressions:
Character Description
\ Marks the next character as either a special character, a literal, a backreference, or an octal escape. For example, 'n' matches the character "n". '\n' matches a newline character. The sequence '\\' matches "\" and "\(" matches "(".
^ Matches the position at the beginning of the input string. If the RegExp object's Multiline property is set, ^ also matches the position following '\n' or '\r'.
$ Matches the position at the end of the input string. If the RegExp object's Multiline property is set, $ also matches the position preceding '\n' or '\r'.
* Matches the preceding subexpression zero or more times. For example, zo* matches "z" and "zoo". * is equivalent to {0,}.
+ Matches the preceding subexpression one or more times. For example, 'zo+' matches "zo" and "zoo", but not "z". + is equivalent to {1,}.
? Matches the preceding subexpression zero or one time. For example, "do(es)?" matches the "do" in "do" or "does". ? is equivalent to {0,1}
{n} n is a nonnegative integer. Matches exactly n times. For example, 'o{2}' does not match the 'o' in "Bob," but matches the two o's in "food".
{n,} n is a nonnegative integer. Matches at least n times. For example, 'o{2,}' does not match the "o" in "Bob" and matches all the o's in "foooood". 'o{1,}' is equivalent to 'o+'. 'o{0,}' is equivalent to 'o*'.
{n,m} m and n are nonnegative integers, where n <= m. Matches at least n and at most m times. For example, "o{1,3}" matches the first three o's in "fooooood". 'o{0,1}' is equivalent to 'o?'. Note that you cannot put a space between the comma and the numbers.
? When this character immediately follows any of the other quantifiers (*, +, ?, {n}, {n,}, {n,m}), the matching pattern is non-greedy. A non-greedy pattern matches as little of the searched string as possible, whereas the default greedy pattern matches as much of the searched string as possible. For example, in the string "oooo", 'o+?' matches a single "o", while 'o+' matches all 'o's.
. Matches any single character except "\n". To match any character including the '\n', use a pattern such as '[.\n]'.
(pattern) Matches pattern and captures the match. The captured match can be retrieved from the resulting Matches collection, using the SubMatches collection in VBScript or the $0$9 properties in JScript. To match parentheses characters ( ), use '\(' or '\)'.
(?:pattern) Matches pattern but does not capture the match, that is, it is a non-capturing match that is not stored for possible later use. This is useful for combining parts of a pattern with the "or" character (|). For example, 'industr(?:y|ies) is a more economical expression than 'industry|industries'.
(?=pattern) Positive lookahead matches the search string at any point where a string matching pattern begins. This is a non-capturing match, that is, the match is not captured for possible later use. For example 'Windows (?=95|98|NT|2000)' matches "Windows" in "Windows 2000" but not "Windows" in "Windows 3.1". Lookaheads do not consume characters, that is, after a match occurs, the search for the next match begins immediately following the last match, not after the characters that comprised the lookahead.
(?!pattern) Negative lookahead matches the search string at any point where a string not matching pattern begins. This is a non-capturing match, that is, the match is not captured for possible later use. For example 'Windows (?!95|98|NT|2000)' matches "Windows" in "Windows 3.1" but does not match "Windows" in "Windows 2000". Lookaheads do not consume characters, that is, after a match occurs, the search for the next match begins immediately following the last match, not after the characters that comprised the lookahead.
x|y Matches either x or y. For example, 'z|food' matches "z" or "food". '(z|f)ood' matches "zood" or "food".
[xyz] A character set. Matches any one of the enclosed characters. For example, '[abc]' matches the 'a' in "plain".
[^xyz] A negative character set. Matches any character not enclosed. For example, '[^abc]' matches the 'p' in "plain".
[a-z] A range of characters. Matches any character in the specified range. For example, '[a-z]' matches any lowercase alphabetic character in the range 'a' through 'z'.
[^a-z] A negative range characters. Matches any character not in the specified range. For example, '[^a-z]' matches any character not in the range 'a' through 'z'.
\b Matches a word boundary, that is, the position between a word and a space. For example, 'er\b' matches the 'er' in "never" but not the 'er' in "verb".
\B Matches a nonword boundary. 'er\B' matches the 'er' in "verb" but not the 'er' in "never".
\cx Matches the control character indicated by x. For example, \cM matches a Control-M or carriage return character. The value of x must be in the range of A-Z or a-z. If not, c is assumed to be a literal 'c' character.
\d Matches a digit character. Equivalent to [0-9].
\D Matches a nondigit character. Equivalent to [^0-9].
\f Matches a form-feed character. Equivalent to \x0c and \cL.
\n Matches a newline character. Equivalent to \x0a and \cJ.
\r Matches a carriage return character. Equivalent to \x0d and \cM.
\s Matches any whitespace character including space, tab, form-feed, etc. Equivalent to [ \f\n\r\t\v].
\S Matches any non-white space character. Equivalent to [^ \f\n\r\t\v].
\t Matches a tab character. Equivalent to \x09 and \cI.
\v Matches a vertical tab character. Equivalent to \x0b and \cK.
\w Matches any word character including underscore. Equivalent to '[A-Za-z0-9_]'.
\W Matches any nonword character. Equivalent to '[^A-Za-z0-9_]'.
\xn Matches n, where n is a hexadecimal escape value. Hexadecimal escape values must be exactly two digits long. For example, '\x41' matches "A". '\x041' is equivalent to '\x04' & "1". Allows ASCII codes to be used in regular expressions.
\num Matches num, where num is a positive integer. A reference back to captured matches. For example, '(.)\1' matches two consecutive identical characters.
\n Identifies either an octal escape value or a backreference. If \n is preceded by at least n captured subexpressions, n is a backreference. Otherwise, n is an octal escape value if n is an octal digit (0-7).
\nm Identifies either an octal escape value or a backreference. If \nm is preceded by at least nm captured subexpressions, nm is a backreference. If \nm is preceded by at least n captures, n is a backreference followed by literal m. If neither of the preceding conditions exists, \nm matches octal escape value nm when n and m are octal digits (0-7).
\nml Matches octal escape value nml when n is an octal digit (0-3) and m and l are octal digits (0-7).
\un Matches n, where n is a Unicode character expressed as four hexadecimal digits. For example, \u00A9 matches the copyright symbol (©).