Hard at work automating tests for your company’s latest application, you abruptly feel a sharp pain in your rump. Almost immediately, you are overcome by feelings of amore. Cupid’s arrow strikes again — but being a testing geek, instead of falling madly in love with a hottie, you are overcome with the desire to automate. Your head fills with the lines of your favorite love poem — How Do I love Thee by Elizabeth Barrett Browning:
lovePoem = “How do I love thee? Let me count the ways.”
lovePoem = lovePoem & “I love thee to the depth and breadth and height”
lovePoem = lovePoem & “My soul can reach, when feeling out of sight”
lovePoem = lovePoem & “For the ends of Being and ideal Grace.”
lovePoem = lovePoem & “I love thee to the level of everydays”
lovePoem = lovePoem & “Most quiet need, by sun and candle-light.”
lovePoem = lovePoem & “I love thee freely, as men strive for Right;”
lovePoem = lovePoem & “I love thee purely, as they turn from Praise.”
lovePoem = lovePoem & “I love thee with a passion put to use”
lovePoem = lovePoem & “In my old griefs, and with my childhoods faith.”
lovePoem = lovePoem & “I love thee with a love I seemed to lose”
lovePoem = lovePoem & “With my lost saints, — I love thee with the breath,”
lovePoem = lovePoem & “Smiles, tears, of all my life! — and, if God choose,”
lovePoem = lovePoem & “I shall but love thee better after death.”
Enthralled, you start furiously typing away in QTP.
You desire to know how many times the word love appears in the poem.
You could use the instr function to find a match and a For Loop to go through the whole poem, but you want a more beautiful solution. The sweet RegEx function comes to mind.
Using RegExp — How to count the number of times the word “love” appears in the poem:
To count the number of times a word (or any pattern) appears in a string, you can use QTP with VBScript’s RegExp object, along with the Pattern property and Execute method.
The Pattern property can set or return any regular expression pattern you wish to search for.
The REgEx Execute method is used to run a search using a regular expression:
re.Global = True
re.Pattern = "love"
Set loveMatch = re.Execute(lovePoem)
You can also use the Replace method to count the appearances of a word or pattern. This method replaces the text found in a search using a regular expression. To replace all the occurrences of the word thee with you in the poem you can do the following:
re.Global = True
re.Pattern = "thee"
(For more detailed info on vbscript regexp check out this site )
Also — QTP 11 has a new feature called “Regular Expression Evaluator” that can be helpful when trying to figure out complicated regexp expressions.
Happy Valentine’s Day all you QTP automation lovers out there!!