JavaScript regular expression longest match (greedy match) and shortest match (lazy match)

Source: Internet
Author: User
Tags expression engine

Recently in reading Requirejs 2.1.15 source code, the source code at the beginning of the definition of a series of variables, there are 4 regular expressions:

var commentregexp =/(\/\* ([\s\s]*?) \*\/| ([^:]|^) \/\/(. *) $)/mg,        cjsrequireregexp =/[^.] \s*require\s*\ (\s*["'] ([^ '" \s]+) ["']\s*\]/g,        jssuffixregexp =/\.js$/,        currdirregexp =/^\.\//;

Commentregexp is used to match the comments in JavaScript code, the use of/M can refer to this article,/g's usage refer to this article. Commentregexp in the *? This usage has not been seen before, it is very strange, because * in the regular expression represents 0 or any number,? represents 0 or 1, just beginning to feel *? This is very superfluous. Ask a colleague to know, *? This is a lazy match.

Alert (/ABC ([\w]*)/mg.exec ("ABC1ABC2") [0]);//abc1abc2alert (/ABC ([\w]*?) /mg.exec ("ABC1ABC2") [0]);//abc


The following code shows the difference between the longest match and the shortest match This code shows the difference between the longest match and the shortest match, one that matches as many characters as possible, and one that matches as few characters as possible. The generic regular expression engine is the longest match by default, and if we want the shortest match, you can add one after the number modifier to the shortest match.

/*** comment 1****/var name = "Aty"; /*** comment 2****/var name = "Aty";

As you can see from the above code, why does the Requirejs match JavaScript annotation take the shortest match mode? If we want to delete all comments, then we should use the shortest match, otherwise var name= "Aty"; This code will be replaced.

JavaScript regular expression longest match (greedy match) and shortest match (lazy match)

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.