TESTEVERYTHING

Showing posts with label RegularExpression. Show all posts
Showing posts with label RegularExpression. Show all posts

Thursday, 4 March 2021

Regular Expression - Documentation

 

Metacharacters

CharacterWhat does it do?
$Matches the end of the input. If in multiline mode, it also matches before a line break character, hence every end of line.
(?:x)Matches 'x' but does NOT remember the match. Also known as NON-capturing parenthesis.
(x)Matches 'x' and remembers the match. Also known as capturing parenthesis.
*Matches the preceding character 0 or more times.
+Matches the preceding character 1 or more times.
.Matches any single character except the newline character.
?
  • Matches the preceding character 0 or 1 time.
  • When used after the quantifiers *, +, ? or {}, makes the quantifier non-greedy; it will match the minimum number of times as opposed to matching the maximum number of times.
[\b]Matches a backspace.
[^abc]Matches anything NOT enclosed by the brackets. Also known as a negative character set.
[abc]Matches any of the enclosed characters. Also known as a character set. You can create range of characters using the hyphen character such as A-Z (A to Z). Note that in character sets, special characters (., *, +) do not have any special meaning.
\
  • Used to indicate that the next character should NOT be interpreted literally. For example, the character 'w' by itself will be interpreted as 'match the character w', but using '\w' signifies 'match an alpha-numeric character including underscore'.
  • Used to indicate that a metacharacter is to be interpreted literally. For example, the '.' metacharacter means 'match any single character but a new line', but if we would rather match a dot character instead, we would use '\.'.
\0Matches a NULL character.
\bMatches a word boundary. Boundaries are determined when a word character is NOT followed or NOT preceeded with another word character.
\BMatches a NON-word boundary. Boundaries are determined when two adjacent characters are word characters OR non-word characters.
\cXMatches a control character. X must be between A to Z inclusive.
\dMatches a digit character. Same as [0-9] or [0123456789].
\DMatches a NON-digit character. Same as [^0-9] or [^0123456789].
\fMatches a form feed.
\nMatches a line feed.
\rMatches a carriage return.
\sMatches a single white space character. This includes space, tab, form feed and line feed.
\SMatches anything OTHER than a single white space character. Anything other than space, tab, form feed and line feed.
\tMatches a tab.
\uhhhhMatches a character with the 4-digits hexadecimal code.
\vMatches a vertical tab.
\wMatches any alphanumeric character incuding underscore. Equivalent to [A-Za-z0-9_].
\WMatches anything OTHER than an alphanumeric character incuding underscore. Equivalent to [^A-Za-z0-9_].
\xA back reference to the substring matched by the x parenthetical expression. x is a positive integer.
\xhhMatches a character with the 2-digits hexadecimal code.
^
  • Matches the beginning of the input. If in multiline mode, it also matches after a line break character, hence every new line.
  • When used in a set pattern ([^abc]), it negates the set; match anything not enclosed in the brackets
x(?!y)Matches 'x' only if 'x' is NOT followed by 'y'. Also known as a negative lookahead.
x(?=y)Matches 'x' only if 'x' is followed by 'y'. Also known as a lookahead.
x|yMatches 'x' OR 'y'.
{n,m}Matches the preceding character at least n times and at most m times. n and m can be omitted if zero..
{n}Matches the preceding character exactly n times.

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[^<]*?>", "" 
 

Wednesday, 13 April 2011

Use Regular Expressions QTP


Some Time QTP not recognize the application object during seond run it Or it run first time successfully then QTP give an error cannot identified the application Window object properties does not match with the test object. there might be a case of window name /object name change each time. Here we required the use of regular expression See the example
Regular Expression
Regular Expression
During Recording of  Flight application QTP record the flight application it identified the Fax order window name property like this
It Text Property is Fax order 11
If you run this script Again it will give an error because Fax order Window name will be
Fax order 12
Regular
Regular
Cannot identify the object “Fax Order No. 11″ (of class Dialog). Verify that this object’s properties match an object currently displayed in your application.
Line (1): “Window(“Flight Reservation”).Dialog(“Fax Order No. 11″).Activate”.
Now we change text property to regular expression open Object properties from object repository  .Click on text property value cell
objectproperty
objectproperty
Check regular expression check box A message will appear click NO. Now change Text box value according to Regular expreesion.
Fax Order No. 11 to Fax Order No.*
Here each time only last part getting changed here we use .* as regular expression means it will check only Fax order No text not whole string
Same case can we apply for different object properties if they getting changed
A regular expression is a string that describes or matches a set of strings. It is often called a pattern as it describes set of strings.
Given underneath is one of the most widely used and ever confused BackLash character. The remaining expressions are serialized below that.
Using the Backslash Character

A backslash (\) instructs QuickTest to treat the next character as a literal character, if it is otherwise a special character. The backslash (\) can also instruct QuickTest to recognize certain ordinary characters as special characters. For example, QuickTest recognizes \n as the special newline character.

For example:

w matches the character w

\w is a special character that matches any word character including underscore

For example, in QTP, while entering the URL of a website,

http://mercurytours.mercuryinteractive.com/

The period would be mistaken as an indication of a regular expression. To indicate that the period is not part of a regular expression, you would enter it as follows:

mercurytours\.mercuryinteractive\.com Note: If a backslash character is used before a character that has no special meaning, the backslash is ignored. For example, \z matches z.
Expressions & Explanation

Special characters and sequences are used in writing patterns for regular expressions. The following describes the characters and sequences that can be used\

Marks the next character as either a special character or a literal. For example, “n” matches the character “n”. “\n” matches a newline character. The sequence “\\” matches “\” and “\(” matches “(“.
^

Matches the beginning of input.
$

Matches the end of input.
*

Matches the preceding character zero or more times. For example, “zo*” matches either “z” or “zoo”.
+

Matches the preceding character one or more times. For example, “zo+” matches “zoo” but not “z”.
?

Matches the preceding character zero or one time. For example, “a?ve?” matches the “ve” in “never”.
.

Matches any single character except a newline character.
(pattern)

Matches pattern and remembers the match. The matched substring can be retrieved from the resulting Matches collection, using Item [0]…[n]. To match parentheses characters ( ), use “\(” or “\)”.
xy

Matches either x or y. For example, “zwood” matches “z” or “wood”. “(zw)oo” matches “zoo” or “wood”.
{n}

n is a nonnegative integer. Matches exactly n times. For example, “o{2}” does not match the “o” in “Bob,” but matches the first two o’s in “foooood”.
{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. 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?”.
[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”.
[^m-z]

A negative range characters. Matches any character not in the specified range. For example, “[m-z]” matches any character not in the range “m” 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 non-word boundary. “ea*r\B” matches the “ear” in “never early”.
\d

Matches a digit character. Equivalent to [0-9].
\D

Matches a non-digit character. Equivalent to [^0-9].
\f

Matches a form-feed character.
\n

Matches a newline character.
\r

Matches a carriage return character.
\s

Matches any white space including space, tab, form-feed, etc. Equivalent to “[ \f\n\r\t\v]“.
\S

Matches any nonwhite space character. Equivalent to “[^ \f\n\r\t\v]“.
\t

Matches a tab character.
\v

Matches a vertical tab character.
\w

Matches any word character including underscore. Equivalent to “[A-Za-z0-9_]“.
\W

Matches any non-word character. Equivalent to “[^A-Za-z0-9_]“.
\num

Matches num, where num is a positive integer. A reference back to remembered matches. For example, “(.)\1″ matches two consecutive identical characters.
\n

Matches n, where n is an octal escape value. Octal escape values must be 1, 2, or 3 digits long. For example, “\11″ and “11″ both match a tab character. “011″ is the equivalent of “01″ & “1″. Octal escape values must not exceed 256. If they do, only the first two digits comprise the expression. Allows ASCII codes to be used in regular expressions.
\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

Translate







Tweet