Measure the test taker's knowledge about the exec and match methods in javascript.

Source: Internet
Author: User

 

This is an article I wrote on csdn. Today I forgot the match feature and found that I had to learn something better.

The difference between the exec and match methods has been somewhat confusing for a long time. Read the help document today (the help document is mainly based on obscure examples to prove it is not helpful to understand ), then I collected some introduction articles from Baidu, the following one (Lou Lan's wind... the exec and match methods in javascript are retrieved multiple times and the first item is searched in Baidu. However, after reading this article, I made some examples to find some problems in the author's conclusions and correct them to avoid misleading you.

1. Before reading the article, I will reference this classic interview question. If you know the answer to the question, you do not need to read it further.

Var someText = "web2.0. net2.0 ";
Var pattern =/(\ w +) (\ d) \. (\ d)/g;
Var outCome_exec=pattern.exe c (someText );
Var outCome_matc = someText. match (pattern );

What is outCome_exec [1] and outCome_matc [1]?

Choice A: true
Choice B: false
Choice C: null
Choice D: Web
Choice E: Web2.0
Choice F: undefined
Choice G: net2.0

 

Think about 1 minute ing ........

 

 

 

 

 

 

Some knowledge has never been used, and it has never been used for two days. If you encounter such a problem, google and Baidu will be the only choice!
2. The thinking has not been completed. Now let's look at the original text and the conclusions in the text:

The original author is as follows:

Http://www.cnblogs.com/xiehuiqi220/archive/2008/11/05/1327487.html

 

The conclusion is as follows:

A) match is an array that returns all matched strings. However, a regular expression must specify the global g attribute to return all matching strings. If the g attribute is not specified, an array with only one element is returned.

B) exec always returns information related to the first match. The returned array includes the first matched string, and the reverse references of all groups.

3. Problems found:

3-1) the above conclusions are incorrect. When using the match method, if g attribute is not specified, it is equivalent to the exec method of the RegExp object, rather than an array with only one element.

Example:

Var str = "ahi ";
Var exp =/a (hi )/;

Var arr1 = exp.exe c (str );
Var arr2 = str. match (exp );
Alert (arr1); // result: arr1.length = 2; arr1 [0] = ahi; arr1 [1] = hi;
Alert (arr2); // result: arr2.length = 2; arr2 [0] = ahi; arr1 [1] = hi; result is the same as above

 

 

3-2) At the same time, when executing the exec method in the js help document, if the property g, set the starting position of the matching object to the character position next to the matching substring. When exec is called for the second time
The character positions indicated by lastIndex start retrieval. Using this feature, you can call exec repeatedly to traverse all the matches. This is equivalent to the case where the match has the g attribute (Actually, the matching result is put into the Matches set.).

Example:

A) when the attribute g exists, the index and lastIndex are updated to play a role in the next search:

Function RegExpTest (){
Var src = "The rain in Spain falls mainly in the plain .";
Var re =/(\ w +)/g; // create the regular expression mode.
Var arr;
While (arr = re.exe c (src ))! = Null ){
Document. write (arr. index + "-" + RegExp. lastIndex + "\ t" + arr [0]); // RegExp. lastIndex and arr. lastIndex has the same attributes and can be exchanged. Note that the lastIndex of IE6 and 7 is set to 0 again.

}
};

RegExpTest ();

// The above example can traverse the matched content. The index and lastIndex of each small match can be obtained;

B) if the above example does not contain g, In the above example, the exec method does not update the global attribute (index, lastIndex, etc.) of the RegExp object, and the above example will be in an endless loop, index and lastIndex are always 0 and 3

 

It can be seen that in the exec process, attribute g can change the values of index and lastIndex to facilitate the next retrieval location. The match method does not have this capability.

 

4. attributes such as index and lastIndex (the help includes leftContext, rightContext, lastMatch, and lastParen (the last parenthesis), but these attributes are based on index and lastindex ).

4-1) read-only attribute.

Example:

Var src = "The rain in Spain falls mainly in the plain .";
Var re =/(\ w +)/g; // create the regular expression mode.
Var arr;
Arr = re.exe c (src );
RegExp. lastIndex = 0;
RegExp. index = 0;
Arr. lastIndex = 0;
Arr. index = 0;

Document. write (arr. index + "-" + arr. lastIndex + "\ t" + arr [0] + "************" + RegExp. index + "-" + RegExp. lastIndex + "\ t" + arr [0]);

// The result is 0-0 The ********** 0-3.

The reason is that the RegExp attribute is read-only. Even if the js language is flexible, you can repair any attribute or add any attribute, and no syntax error is reported. However, the RegExp attribute cannot be changed, but the arrary object can be changed. However, every time you execute exec, attributes such as RegExp. index will be assigned a new value to the returned Arrary object.

For example:

Var src = "The rain in Spain falls mainly in the plain .";
Var re =/(\ w +)/g; // create the regular expression mode.
Var arr;
Arr = re.exe c (src );
RegExp. lastIndex = 0;
RegExp. index = 0;
Arr. lastIndex = 0;
Arr. index = 0;

Document. write (arr. index + "-" + arr. lastIndex + "\ t" + arr [0] + "************" + RegExp. index + "-" + RegExp. lastIndex + "\ t" + arr [0]);

// The index attribute of the second arr execution will be updated. In fact, when the RegExp object instance executes the exec method, it will update the global RegExp. index and arr index.

Arr = re.exe c (src );
Document. write ("<br/>" + arr. index + "-" + arr. lastIndex + "\ t" + arr [0] + "************" + RegExp. index + "-" + RegExp. lastIndex + "\ t" + arr [0]);

// 0-0 The ********** 0-3
// 4-8 rain *********** 4-8 rain

4-2) when different RegExp instance objects cross execute exec, attributes such as index and lastIndex do not affect each other. Each time the exec or String match method is executed, a new value is assigned to RexExp. index and so on. (This is actually necessary, but I am confused about it. I am wrong to understand it, mainly because "RegExp. lastIndex = 0; "can be assigned a value, but the result does not change when the value is set, which makes my head messy .)

 

At first, I thought that if two RegExp objects cross-Execute exec, the index may be cleared. Because I think the index attribute is saved on the Global static attribute of RegExp. It is found that it is stored in a specific RegExp instance. Each time you execute exec or the String match method, a new value will be assigned to RexExp. index and so on.

Haha, this may be a common mistake that people get used to the ideas of classes and class instances in c and java think RegExp is a class, and RegExp. index is a static attribute of a class. This is true, but its value is updated by the regular object when the exec and String match methods are executed.

Example:

Var src = "The rain in Spain falls mainly in the plain .";

Var re1 =/(\ w +)/; // create the regular expression mode.
Var re2 =/(\ w +)/g; // create the regular expression mode.
Var arr;

Arr = re1.exec (src );
Document. write ("R1 first execute exec:" + RegExp. index + "-" + RegExp. lastIndex + "\ t" + arr [0]);

Arr = re2.exec (src );
Document. write ("<br/> R2 executes exec for the first time:" + RegExp. index + "-" + RegExp. lastIndex + "\ t" + arr [0]);

Arr = re1.exec (src );
Document. write ("<br/> R1 executes exec for the second time:" + RegExp. index + "-" + RegExp. lastIndex + "\ t" + arr [0]);

Arr = re2.exec (src );
Document. write ("<br/> R2 executes exec for the second time:" + RegExp. index + "-" + RegExp. lastIndex + "\ t" + arr [0]);

The output result is as follows:

R1 executes exec FOR The first time: 0-3
R2 executes exec FOR The first time: 0-3
R1 executes exec for The second time: 0-3
R2 executes exec for the second time: 4-8 rain

 

4-3) The match Method of the String object cannot obtain the index and lastIndex of the object to be searched in the middle as the exec method, that is, it is one-time. That is, the location of the next search cannot be obtained. The match method can only obtain the last search, index, and lastIndex when setting the g attribute. When the match method does not set the g attribute, obtain only the first matched index and lastIndex.

Example:

A)

Var src = "The rain in Spain falls mainly in the plain .";
Var re =/\ w +/g; // has the g attribute.
Var I = 0;
While (I ++ <10 ){
Arr = src. match (re );
Document. write (RegExp. index + "-" + RegExp. lastIndex + "\ t" + arr + "<br/> ");

}

// The result is as follows:

38-43 The, rain, in, Spain, falls, mainly, in, the, plain
38-43 The, rain, in, Spain, falls, mainly, in, the, plain
38-43 The, rain, in, Spain, falls, mainly, in, the, plain
38-43 The, rain, in, Spain, falls, mainly, in, the, plain
38-43 The, rain, in, Spain, falls, mainly, in, the, plain
38-43 The, rain, in, Spain, falls, mainly, in, the, plain
38-43 The, rain, in, Spain, falls, mainly, in, the, plain
38-43 The, rain, in, Spain, falls, mainly, in, the, plain
38-43 The, rain, in, Spain, falls, mainly, in, the, plain
38-43 The, rain, in, Spain, falls, mainly, in, the, plain

 

B)

Var src = "The rain in Spain falls mainly in the plain .";
Var re =/\ w +/; // No g attribute.
Var I = 0;
While (I ++ <10 ){
Arr = src. match (re );
Document. write (RegExp. index + "-" + RegExp. lastIndex + "\ t" + arr + "<br/> ");

}
// The result is as follows:

0-3
0-3
0-3
0-3
0-3
0-3
0-3
0-3
0-3
0-3

C)

Var src = "The rain in Spain falls mainly in the plain .";
Var re =/\ w +/g;
Var I = 0;
Arr = src. match (re );
While (arr [I]! = Null ){
Document. write (RegExp. index + "-" + RegExp. lastIndex + "\ t" + arr [I] + "<br/> ");
I ++;
}
// The result is as follows:

38-43
38-43 rain
38-43 in
38-43 Spain
38-43 falls
38-43 mainly
38-43 in
38-43
38-43 plain

5. Final conclusion (correct if any ):

1) exec is the RegExp object method, and match is the String object method;

2) If no result is found, both return null;

3) only when the regular expression must specify the global g attribute can match be returned. Otherwise, there is no difference between the match and exec method results, which is equivalent;

4) exec always returns information related to the first match. The first value of the returned array is the first matched string, the rest is the reverse reference of all groups (that is, the matching content of the parentheses );

5) After exec sets the g attribute, although the matching result is not affected by g, the returned result is still an array (the first value is the first matched string, but it will change the index and lastIndex values, and set the starting position of the matching of the object to the character position next to the matching substring, when exec is called for the second time, it is retrieved from the character position indicated by lastIndex. Similarly, after the g attribute is set for the match method, the values of index and lastIndex are also changed, but the value is one-time. It is impossible to accumulate by process like exec (the result is put into the Matches set), so it is impossible to accumulate the location for the next retrieval.

 

PS:

The answer to the first question is D and G. Do you want to understand?

The above tests are all tested in ie and firefox, and the results are consistent.

The premise of the above test is that javascript supports RegExp objects. Early browser javascript Engines may not support regular objects or some attributes of Regular Expression objects.

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.