The regular expression or RegEx is a very powerful tool to find a matching pattern of string in a given string or find a substring in a string. In this article, I will show you how to use regular expression in UFT to check whether any MASTER or a VISA card account number is present in a given string. You can use this example to do similar kinds of things.
Regular Expression to find a matching pattern of String
A Master or Visa card is a 16 digit number. A Visa Card starts with the number 4 and a Master Card starts with 5. The rest of the numbers could be anything between 0 to 9. The following function will find all matching card numbers in the given string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
Function GetAllMatchingCard(strVar) Set regEXP = CreateObject("vbscript.regexp") regEXP.Pattern = "[45][0-9]{15}\s" 'RegEx pattern to find out Visa and Master card regEXP.Global = True 'True matches all occurances strTemp = "" If regEXP.Test(strVar) Then Set matches = regEXP.Execute(strVar) For Each Match In matches strTemp = strTemp & "Position " & Match.FirstIndex & " Matching Word: " & Match.Value strTemp = strTemp & ";" Next GetAllMatchingCard = strTemp Else GetAllMatchingCard = "" End If End Function |
In the variable strVar a string value has been stored containing two Master Card Numbers.
I am calling the GetAllMatchingCard() function that would display the position and values of the Master cards in the string.
1 2 3 |
strVar = "5670181234599078 or 457989889 5670181234599076 " MsgBox GetAllMatchingCard(strVar) 'Calling GetAllMatchingCard function |
The output would be as follows.
A couple of points to be remembered. If you are searching a text value within a string then set the following things to regEXP object.
1 2 3 |
regEXP.IgnoreCase = True 'True to ignore case regEXP.MultiLine = True 'True will check the required pattern in |
When to use the Regular Expression in String Manipulation
- You have to validate all instances of a word in a file.
- You have to find a specific pattern of words in a file.
- You have to find a specific pattern of words in a file and replace them with some other value.
Recommended Posts
- How to Use Regular Expression in UFT to Identify an Object
- File System Object UFT | VBA
- All You Need to Know About Object Identification in UFT
- How to Load Function Libraries at runtime in UFT
- How to Record a Script in Chrome Browser in UFT
- Delete Browser Cookie, Cache, and History in UFT
- How to Use WaitProperty | Dynamic Wait in UFT
- Read and Update XML File in UFT | VBA
- VBScript Loops: Do Loop, For Loop, For Each, and While Loop
- VBScript MySQL Database Connection in UFT