Regular Expression object and Regexp object

Source: Internet
Author: User

Regular Expression object and Regexp object

The regular expression object is used to find the character combination mode in a string. After a regular expression object is created, it is passed to the string method, or the string is passed to a regular expression method. The information about the latest search is saved in the Regexp object.

There are two methods to create a regular expression object. If you know the string to be searched in advance, use Syntax 1:

VaR regularexpression =/Pattern/[Switch]

Use syntax 2 when the search string is frequently changed or unknown:

VaR regularexpression =New Regexp ("Pattern",["Switch"])

Pattern is the string to be searched. It is enclosed by a slash in Syntax 1 and enclosed by quotation marks in syntax 2. Switch is a switch. There are three options: "I" indicates case-insensitive, "G" indicates all the pattern in full-text search, and "Gi" indicates both, that is, full-text search and case-insensitive.

Execute search

After creating a regular expression objectExecMethod, Syntax:

Rgexp.Exec (Str)

Rgexp is a regular expression object, which can be a variable name or text. StrIs the string to be searched. For example,

VaR S = "aabbccddeeffgghhiijjkkllmmnnoopp ";
VaR r = new Regexp ("g", "I ");
VaR A = r.exe C (s );
Document. Write (a); // display g

The case sensitivity is ignored, and the first matching is g after the search is executed, so the variable A = "G ".

ExecThe result of the Method Search is placed in an array. IfExecIf the method does not find a match, it returnsNull. If it finds one or more matchesExecMethod returns an array and updates it.RegexpObject To reflect the search results. InRegexpThe last nine results are saved in the property $1,... $9 of the object. The value of $1... $9 attribute is modified at any time, but only the last nine values can be saved.

Test the regular expression mode.

You can use the test method to test whether a regular expression exists in the string to be queried. Syntax

Rgexp.Test (Str)

Syntax andExecSame method. It returns a Boolean value. If yes, true is returned. Otherwise, false is returned.TestMethod not modifiedRegexpObject.

Regexp object and its attributes

The Regexp object is used to save the information for regular expression mode lookup, which is kept in its attributes. Regexp object has no method. The general syntax is

Regexp.Propertyname

PropertynameThe parameter isRegexpAn attribute of an object.RegexpObjects have the following attributes:

$1-$9 attributesReturns nine recently saved parts found during the pattern matching. Read-only.
Regexp. IndexReturns the starting position of the First successfully matched string.
Regexp. lastindexReturns the starting position of the last successful match in the string to be searched.
Regexp. Input
Returns the string to be searched. Read-only.

The lastindex attribute is based on zero, that is, the index of the first character is zero. The value of a successful match is modified at any time. The lastindex attribute is modified by the exec and test methods of the Regexp object, as well as the match, replace, and split Methods of the string object.

The following rules apply to the value of lastindex:

  • If no match exists, lastindex is set to-1.
  • If lastindex is longer than the string length, test and exec fail, and lastindex is set to-1.
  • If lastindex is equal to the length of the string and the pattern matches the null string, the regular expression matches. Otherwise, the match fails and the lastindex is reset to-1.
  • Otherwise, lastindex is set to the next location of the nearest match.

The code below routine 1 is used to evaluate the content of the above attributes.

Function regexpdemo (Reg, STR ){
VaR Re = new Regexp (Reg, "Gi ");
VaR A = re.exe C (STR );
VaR BR = "<br> ";
If (Re. Test (STR ))
Document. Write ("the first matched string found is" + A + Br );
Document. Write ("the first matching position is" + Regexp. index + Br );
Document. Write ("the last matching position is" + Regexp. lastindex + Br );
Document. Write ("the searched text is:" + Br + Regexp. Input + Br );
Document. Write ("$1 =" + Regexp. $1 );
};
VaR STR = "the built-in objects are special because they are built into ASP pages and do not need to be created before you can use them in scripts .";
VaR Reg = "(object )";
Document. Write ("Search" + Reg + "<br> ");
Regexpdemo (Reg, STR + Str );

Running routine

DescriptionThe searched String object is enclosed in parentheses and $1 has a value. $1 is an empty string without parentheses. Why? I don't know.

Attributes of a regular expression object

A regular expression object has two attribute attributes.LastindexAttribute specifies the index. The next match starts from the index. Syntax:

Rgexp.Lastindex[=Index]

SeeRegexpObjectLastindexAttribute.

SourceAttribute returns a copy of the text in regular expression mode, read-only. Syntax:

Rgexp.Source

The example below illustratesSourceAttribute usage:

Function sourcedemo (Re, S) {var S1; // test whether a regular expression exists in the string. If (Re. test (s) S1 = "contains"; elses1 = "does not contain"; // obtain the text of the regular expression. Return (S + S1 + RE. source );

Regexp. InputReturns the string to be searched, whileSourceIs the string to be searched.

Compile method of the regular expression object

Regular Expression ModePatternParameters are compiled into the internal format before they are used. For Syntax 1,Pattern The script is compiled when it is loaded. For syntax 2,PatternBefore use, or callCompileMethod is compiled. The compile method converts pattern to an internal format to perform faster. This makes it more effective to use regular expressions in a loop. Syntax:

Rgexp.Compile (Pattern)

The example below illustratesCompileMethod usage:

Function compiledemo () {var S = "aabbccddeeffgghhiijjkkllmmnnoopp" // create a regular expression for only uppercase letters. VaR r = new Regexp ("[A-Z]", "G"); var A = S. Match (r) // find matching. Document. Write (a); R. Compile ("[A-Z]", "G"); // compile the regular expression only for lowercase letters. VaR A = S. Match (r) // search for matching. Document. Write ();}

Code comment

Match isStringAn object method. Its function is to useRegular ExpressionThe object searches for the string and returns the result as an array. Syntax:

Stringobj.Match (Rgexp)

MatchMethod andRegexp.exe CReturns an array. Element 0 of the array contains the final matched characters, element 1...NContains content that matches any substring separated by an insertion in the regular expression. This method will be updatedRegexpObject content.

The following example demonstratesMatchMethod usage:

function MatchDemo(){var r, re;var s = "The quick brown fox jumped over the lazy yellow dog.";re = /fox/i;r = s.match(re);return(r);}

Regular Expressions in VBScript

In VBScript, the regular expression object isRegexpObject. The Regexp object has three attributes:

  • PatternAttribute to set or return the regular expression pattern to be searched.
  • Global Attribute, indicating whether to match all or only the first character string in the search mode.
  • Ignorecase Attribute, indicating whether the mode search is case sensitive.

Regexp objects have three methods:

  • Object. Execute (String)Perform regular expression search on the specified string. The execute method returns a matches set, which contains each matching match object found in the string. If no match is found, execute returns an empty matches set.
  • Object. Test (String)Perform a test search on the specified string. Only one Boolean value is returned to indicate whether a match exists.
  • Object. Replace (String1,String2)Replace the text found in the regular expression. Search for string1 and replace it with string2. Returns the string after string1 is replaced.

Here, the object is a defined Regular Expression and the string is the text to be searched. To searchPatternThe regular expression mode of the description.

Routine 1 creates a regular expression and demonstrates the replacement method.

Function ReplaceTest(patrn, replStr)Dim regEx, str1str1 = "The quick brown fox jumped over the lazy dog."Set regEx = New RegExpregEx.Pattern = patrnregEx.IgnoreCase = TrueReplaceTest = regEx.Replace(str1, replStr)End FunctionMsgBox(ReplaceTest("fox", "cat"))
Please copy this routine and run it on your own.

Match object andMatchesSet

It can only be created through the execute method of the Regexp object. This method actually returns a set of matching objects.Matches. All the matching object attributes are read-only. Each match object provides the starting position, length, and other information of the matching string found by the regular expression search, and is accessible to users through the attributes of the match object.

  • FirstindexThe matched position in the search string.
  • LengthThe length of the matched string.
  • ValueThe matched string.

Routine 2 creates a regular expression, executes the search, and displays the matching results.

Function regexptest (patrn, strng)
Dim RegEx, match, matches
Set RegEx = new Regexp
RegEx. pattern = patrn
RegEx. ignorecase = true
RegEx. Global = true
Set matches = RegEx. Execute (strng)
For each match in matches
Retstr = retstr & "match" & Match & "found at position"
Retstr = retstr & Match. firstindex & ". Match value is"
Retstr = retstr & Match. Value & "'." & "<br>"
Next
Regexptest = retstr
End Function
Document. Write (regexptest ("is.", "is1 is2 is3 is4 "))

Running routine 2

Usage of Regular Expressions in two languages

Regexp object of VBScript Regular Expressions in Javascript
Ignorecase attributes Create switch = "I" in the syntax"
Global attributes Create switch = "G" in the syntax"
Pattern attributes Create the pattern parameter in the syntax
Matchs object set Attribute $1-$9
Execute Method Exec Method
Test Method Test Method
Replace Method There is no corresponding method, but there is a string object's replace Method
No corresponding method Compile Method
No corresponding attribute SourceAttribute

There are many special characters used in the regular expression mode, which are the same in both languages. For more information, see related articles.

Wendongfang Yifeng 2002-12-27

URL: http://www.shps.cn/developweb/webSchool/VBJAVA/VBJjc016.htm
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.