This article mainly introduces the use of the js Regular Expression longest match (Greedy match) and shortest match (lazy match, this article analyzes the specific usage and precautions of greedy matching and lazy Matching Based on the instance form. For more information, see the examples in this article) and the use of the shortest match (lazy match. We will share this with you for your reference. The details are as follows:
I recently read the source code of RequireJS 2.1.15. A series of variables are defined at the beginning of the source code. There are four regular expressions:
var commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,jsSuffixRegExp = /\.js$/,currDirRegExp = /^\.\//;
CommentRegExp regular is used to match comments in JavaScript code. for usage of/m, refer to this article: Analysis of multiline (/m) usage in JS Regular Expression modifiers. for usage of/g, refer to this article: analysis of JS Regular Expression modifier global (/g) usage. *? In commentRegExp *? This usage has never been seen before, and it is very strange, because * represents 0 or any number of regular expressions ,? 0 or 1. At first, I thought *? There are a lot of such statements. 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 differences between the longest match and the shortest match. The code shows the differences between the longest match and the shortest match. A match can contain as many characters as possible, match as few characters as possible. Generally, the Regular Expression Engine is the longest match by default. If we want the shortest match, we can add? To the shortest match.
/***** Comment 1 *****/var name = "aty";/***** comment 2 *****/var name = "aty ";
Through the above code, we can see why does requirejs use * to match javascript annotations *? This is the shortest matching mode. If we want to delete all comments, we should adopt the shortest match, otherwise var name = "aty"; this code will be replaced.
For more articles on the use and analysis of js Regular Expressions longest matching (Greedy matching) and shortest matching (lazy matching), refer to PHP Chinese website!