Regular-expression match and Exec comparisons

Source: Internet
Author: User

Match and exec differ in two main points:

1.exec is a method of a regular expression, not a method of a string, and its argument is the string, as follows:

var re=New RegExp (/\d/"abc4def" );

Or use the Perl style:

" Abc4def " );

Match is the method provided by the string class, and its arguments are regular expression objects, and the following usage is correct:

" Abc4def ". Match (\d);

Or

" Abc4def ". Match ("ABC");

2.exec and match return all arrays

    • The regular expression that executes the Exec method is not grouped, so if there is a match, he will return an array with only one element, or null if there is no match.
    • exec does not support I m g

The following two alert functions pop up with the same message:

var " Cat,hat "  ; var // No G attribute Alert (p.exec (str))//["at"]alert (Str.match (P))// ["at"]

Then the exec and match methods are equal

var " Cat,hat "  ; var // Note the G property Alert (p.exec (str))// ["at"]
alert (Str.match (P))// [' at ', ' at ']

Because exec always returns only the first match, and match returns all matches when the G attribute is specified in the regular.

exec if a match is found and contains a grouping , the returned array will contain more than one element, the first element being the match found, followed by the first and second of the matching elements. Group (reverse reference)
The following code will pop up "Cat2,at":

var " cat2,hat8 "  ; var p=/c (at) \d/; alert (p.exec (str))//[' Cat2 ', ' at ']

The match function implements the same functionality as exec when it meets the following conditions: someone else

    • 1, the regular expression contains the grouping (parentheses)
    • 2, return the only match, do not use g,m time
var " cat2,hat8 "  ; var p=/c (at) \d/; alert (p.exec (str))//[' Cat2 ', ' at ']alert (Str.match (p))//[' Cat2 ', ' at ']
var p=/c (at) \d/g;
Alert (Str.match (p))//["Cat2", "at"]



  

Regular-expression match and Exec comparisons

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.