RegExp object in JS Regular Expressions

Source: Internet
Author: User

You can create an instance of the RegExp object in two ways.

Use RegExp's explicit constructor. Syntax: new RegExp ("pattern" [, "flags"]).
Use RegExp's implicit constructor in plain text format:/pattern/[flags].

The pattern part is required for the regular expression pattern text to be used. In the first method, the pattern part exists as a JavaScript string and must be enclosed by double quotation marks or single quotation marks. In the second method, the pattern part is nested between two, quotation marks are not allowed.

The flags part sets the Flag Information of the regular expression, which is optional. If the flags part is set, it exists as a string in the first method; in the second method, it follows the last "/" character in the text form. Flags can be a combination of the following flag characters.
G is the global flag. If this flag is set, the search and replacement operations on a text will take effect for all matching parts of the text. If this flag is not set, only the first matched content is searched and replaced.

I is a case-insensitive flag. If this flag is set, Case sensitivity is ignored during Matching and comparison.

M is a multiline flag. If this flag is not set, the metacharacter "^" only matches the start position of the searched string, the metacharacter "$" only matches the end position of the string to be searched. If this flag is set, "^" can also match the position after "\ n" or "\ r" in the searched string (that is, the beginning of the next row, "$" can also match the position after "\ n" or "\ r" in the searched string (that is, the end of the next row.

Code 1.1 is an example of creating a regular expression.
Code 1.1 create a regular expression: 1.1.htm

Copy codeThe Code is as follows:
<Html>
<Head>
<Title> Create a regular expression </title>
<Script language = "JavaScript">
Var myString = "This is the first regular expression example ";
Var myregex = new RegExp ("one"); // create a regular expression
If (myregex. test (myString )){
Document. write ("the specified mode is found! ");
}
Else {
Document. write ("the specified mode is not found. ");
}
</Script>
</Head> <body> </body>
</Html>

The running result of the code above is 8.1.
Because "\" in the JavaScript string is an escape character, when you use an explicit constructor to create a RegExp instance object, replace "\" in the original regular expression. For example, two statements in Code 1.2 are equivalent.
"\": 1.2.htm In the Escape Character of Code 1.2
Copy codeThe Code is as follows:
<Script language = "javascript">
Var re1 = new RegExp ("\ d {5 }");
Var re2 =/\ d {5 }/;
Alert ("re1 =" + re1 + "\ nre2 =" + re2 );
</Script>

Because the Escape Character in the regular expression mode text is "\", if the regular expression must match the original character "\", the regular expression mode text must be represented by "\". When you create a RegExp Instance Object using an explicit constructor, you need to use "\" to represent the original literal character "\".
Var re = new RegExp (\\\\).

1. RegExp Object Attributes

RegExp object attributes include static attributes and instance attributes. The following is an introduction.

1.1 static attributes
(1) index attribute. It is the starting position of the First Matching content in the current expression mode and starts from 0. The initial value is-1. The index attribute changes every successful match.
(2) input attribute. Returns the current string, which can be abbreviated as $ _. The initial value is an empty string "".
(3) lastIndex attribute. It is the next position of the last character in the first match of the current expression mode, which starts from 0 and is often used as the starting position for continued search. The initial value is-1, it indicates that the search starts from the starting position. The value of the lastIndex attribute changes each time the matching is successful.
(4) lastMatch attribute. Is the last matching string of the current expression pattern, which can be abbreviated as $ &. Its initial value is an empty string "". The attribute value of lastMatch changes after each successful match.
(5) lastParen attribute. If the enclosed child match exists in expression mode, it is the substring matched by the final child match in the current expression mode, which can be abbreviated as $ +. Its initial value is an empty string "". The value of the lastParen attribute changes each time a successful match is made.
(6) leftContext attribute. Is all content on the left of the last matching string in the current expression mode. It can be abbreviated as $ '("'" indicates the reverse quotation mark under "Esc" on the keyboard ). The initial value is an empty string "". The attribute value of each successful match changes accordingly.
(7) rightContext attribute. Is all content on the right of the last matched string in the current expression mode, which can be abbreviated as $ '. The initial value is an empty string "". The attribute value of each successful match changes accordingly.
(8) $1... $9 attribute. These attributes are read-only. If the expression mode contains the enclosed child match, $1... The $9 attribute values are the content captured by 1st to 9th child matches. If more than 9 Child matches exist, $1... The $9 attribute corresponds to the last nine Child matches. In an expression mode, you can specify any number of child matches with parentheses, but the RegExp object can only store the last nine Child matches. In the result array returned by some methods of the RegExp instance object, you can obtain the child matching results in All parentheses.

1.2 instance attributes

(1) global attributes. Returns the status of the global sign (g) specified when the RegExp object instance is created. If the g flag is set when the RegExp object instance is created, True is returned for this attribute. Otherwise, False is returned. The default value is False.
(2) ignoreCase attributes. Returns the status of the ignoreCase flag (I) specified when the RegExp object instance is created. If the I flag is set when the RegExp object instance is created, True is returned for this attribute. Otherwise, False is returned. The default value is False.
(3) multiLine attributes. Returns the status of the multiLine flag (m) specified when the RegExp object instance is created. If the m flag is set when the RegExp object instance is created, True is returned for this attribute. Otherwise, False is returned. The default value is False.
(4) source attribute. Returns the expression text string specified when the RegExp object instance is created.

RegExp object in JS (2)

2. RegExp object Method
Common RegExp object methods include test, exec, and compile. This section describes the functions and usage of these methods. Finally, we provide a comprehensive example of RegExp object attributes and methods.
2.1 test Method
The syntax format is test (str ). This method checks whether a string contains the expression mode specified when the RegExp object instance is created. If yes, True is returned; otherwise, False is returned. If a match is found, the static attributes in the RegExp object are updated to reflect the match.
2.2 exec Method
The syntax format is exec (str ). This method searches a string using the expression mode specified when the RegExp object instance is created, and returns an array containing the search results.
If a global sign (g) is set for the regular expression, you can perform a continuous search in the string by calling the exec and test Methods multiple times, each time, the string is searched from the location specified by the value of the lastIndex attribute of the RegExp object.
If the global flag is not set, the exec and test Methods ignore the lastIndex attribute value of the RegExp object and start searching from the start position of the string.
If the exec method does not find a match, the return value is null. If a match is found, an array is returned and the static attributes in the RegExp object are updated to reflect the match. Element 0 in the returned array contains the complete matching result, while element 1 ~ N is the result of each sub-match defined in expression mode in sequence.
The array returned by the exec method has three attributes: input, index, and lastIndex.
The input attribute is the entire searched string.
The index attribute refers to the position in the searched string.
The lastIndex attribute indicates the next character position of the last character of the matched substring.
Code 2.1 is an example of the application of this method.
Code 2.1 exec () method application: 2.1.htm
Copy codeThe Code is as follows:
<Html>
<Head>
<Title> exec () method application </title>
<Script language = "JavaScript">
Var myString = "aaa 111 bbb 222 ccc 1111 222ddd ";
Var regex =/111/; // create a regular expression object
Var array=regex.exe c (myString );
If (array ){
Var str = "matched substring found! "+" \ N returned array value: "+ array +" \ n array Element count :"
+ Array. length + "\ n searched string:" + array. input
+ "\ N matched substring start position:" + array. index
+ "\ N: the first character behind the matched substring is:" + regex. lastIndex;
Alert (str );
}
Else {
Alert ("matched substring not found !! ");
}
</Script>
<Body> </body>
</Html>

2.3 compile Method

The syntax format is compile ("pattern" [, "flags"]). This method can replace the expression mode used by the RegExp object instance and compile the new expression mode into an internal format, so that later matching can be executed faster. If you want to reuse an expression in a loop, compiling it will accelerate execution. However, if any other expression mode is used in the program and then the compiled expression mode is used, this compilation will be of no benefit.

2.4 Comprehensive examples

Code 2.2 is a comprehensive example of RegExp objects. By carefully analyzing the Code and its running results, you can better understand RegExp objects.
Code 2.2 Use of RegExp object: 2.2.htm
Copy codeThe Code is as follows:
<Script language = "javascript">
Var strSrc = "xxa1b01c001yya2b02c002zz ";
Var re =/a (\ d) B (\ d {2}) c (\ d {3})/gi;
Var arr, count = 0;
While (arr = re.exe c (strSrc ))! = Null)
{
DisplayResult ();
}
Function displayResult ()
{
Document. write ("<p> This is a string using a regular expression/" + re. source + "/gi <br> ""
+ RegExp. input + "" perform the "+ (+ + count) +" secondary search result: <br> ");
Document. write ("RegExp. index is" + RegExp. index + "<br> ");
Document. write ("RegExp. lastIndex is" + RegExp. lastIndex + "<br> ");
Document. write ("RegExp. lastMatch is" + RegExp. lastMatch + "<br> ");
Document. write ("RegExp. lastParen is" + RegExp. lastParen + "<br> ");
Document. write ("RegExp. leftContext is" + RegExp. leftContext + "<br> ");
Document. write ("RegExp. rightContext is" + RegExp. rightContext + "<br> ");
Document. write ("RegExp. $1 is" + RegExp. $1 + "<br> ");
Document. write ("RegExp. $2 is" + RegExp. $2 + "<br> ");
Document. write ("RegExp. $3 is" + RegExp. $3 + "<br> ");
Document. write ("RegExp. $4 is" + RegExp. $4 + "<br> ");
Document. write ("arr. index is" + arr. index + "<br> ");
Document. write ("arr. input is" + arr. input + "<br> ");
Document. write ("arr. lastIndex is" + arr. lastIndex + "<br> ");
Document. write ("the number of elements in the returned array is" + arr. length + "<br> ");
Document. write ("the returned array content is ["];
For (var I = 0; I <arr. length; I ++)
{
If (I <arr. length-1)
Document. write ("" + arr [I] + "",");
Else
Document. write ("" + arr [I] + "") </p> ");
}
}
</Script>

Related Article

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.