JavaScript series Article: detailed Jiu Zheng expression of the second

Source: Internet
Author: User
Tags modifier modifiers uppercase letter

In the previous article we talked about the basic use of regular expressions, and then the blogger wants to talk about the details, starting with the regular modifier today.

The regular modifier, also known as the regular tag (flags), defines the regular matching rule, which in turn affects the final result of the Match. In the last article we also mentioned that there are a total of the following types of regular modifiers, which can be used alone or combined:

// Global Search // Ignore case // multi-line // Unicode // Sticky/\w+/gi; New RegExp (' \\w+ ', ' gi ');

One of them is good to understand, as in the above comment, the ignore case or insensitive, ignoring casing.

The following is a simple example where a regular expression with an I modifier can also be matched to an uppercase Letter:

' Hello World '. match (/hello/i);  // ["hello"]/hello/i.exec (' Hello World ');   // ["Hello"]

Look again at the global match modifier g, Below is an example of a global match:

var source = ' Hello world hello JS '; Source.match (/hello/);      // ["hello"] Source.match (/hello/g);     // ["hello", "hello"]

As can be seen from the above code, there is only one match for normal regular, if you want to find out all the matching results, then you need to add a G modifier to make it a global matching pattern.

The global modifier g will also be used in conjunction with the multiline match modifier m, and we'll make a slight change to the above example, adding a newline character, and the regular modification:

var source = ' Hello World\nhello JS '; Source.match (/^hello.+/g);    // ["hello world"]

As you'll see, we're going to match the string that starts with "hello" in the multiline text, but the result is only the first match, and the following "hello JS" doesn't match, and we need to add the multiline match modifier m:

var source = ' Hello World\nhello JS '; Source.match (/^hello.+/gm);   // ["hello world", "hello JS"]

now, all the results are Matched.

however, It is important to note that the use of the modifier m alone does not work, it must be combined with the g, as in the following example, although there are M modifiers, but still only match to the first line of Text:

var source = ' Hello World\nhello JS '; Source.match (/^hello.+/m);    // ["hello world"]

In addition, there is a very important condition, that is, only the regular contains the start tag "^" or the end tag "$", modifier M will play its role, otherwise G does not need m, and see the following example:

//g only needs m when matching start tag ^ or end tag $varSource = ' Hello World\nhey world ';//No ^ or $ just g to match multiple lines in regularSource.match (/he.+/g);//["hello world", "hey world"]//Regular contains ^ or $ g can only match the first resultSource.match (/^he.+/g);//["hello world"]Source.match (/.+world$/g);//["hey world"]//you need to add m in case of ^ or $ to match multiple linesSource.match (/^he.+/gm);//["hello world", "hey world"]Source.match (/.+world$/gm);//["hello world", "hey world"]

All of the above describes the regular modifier in the String#match () method, We also know that regexp#exec () is a corresponding method, the same can match the string, return the result array, then this exec () How does the method behave for a regular that contains global modifiers? The actual operation found that the Regexp#exec () method is roughly the same as the rules above String#match (), But the difference is that the Regexp#exec () method will only match one result at a time, so multiple loop execution is required to get All. Let's look at the following example:

var regex =/^hello.+/gm; var source = ' Hello World\nhello JS '; regex.exec (source);    // ["hello world"]regex.exec (source);   // ["hello JS"]

You can see that each exec () method that executes the regular instance returns an array of results, and since the regular contains the start tag ^ and the GM combination, we need to execute two times to get the full result, which is different from the String#match () method. In general, we can call the Regexp#exec () method with the loop structure to get all the results:

var NULL ;  while (result = regex.exec (source)) {  console.log (result);} // output: // ["hello world"] // ["hello JS"]

For the regexp#test () method, It is generally used to detect whether a string matches a pattern, if you want to detect any row in a row is a match, the same need for the GM combination, The following code is a simple detection of the match, and then in the multi-line matching:

var source = ' Hello World\nhey JS '; /^hello.+/.test (source);      // true/^hey.+/.test (source);        // false/^hey.+/g.test (source);       // false/^hey.+/gm.test (source);      // true

From the results, without the GM modifier of the regular, can only detect the matching of a row of data, after the addition of GM can be detected on multiple lines, as long as any row matches the condition, that is, return True.

and finally, the String#replace () method, similarly, If ^ or $ is present in the regular, then you need to add a GM combination, The following code shows the operation of the multiline substitution:

var source = ' Hello World\nhello JS '; // there is no ^ or $ in the regular, global G easy to fix source.replace (/hello/g, ' Hey ');    // "hey World\nhey JS" // the Regular contains ^ or $, global G is powerless, can only replace the first line source.replace (/^hello/g, ' Hey ');   // "hey World\nhello JS" // need to use GM combination source.replace (/^hello/gm, ' Hey ');  // "hey World\nhey JS"

Above is the global match G and multi-line matching m, the following describes the U modifier.

The U modifier is a ES6 new feature that enables Unicode mode to match strings in a regular way and correctly handles the Four-byte UTF-16 character Set. Why this modifier is needed, let's look at an example:

/^. {3}$/.test (' Hello ');    // true/^. {3}$/.test ('??? Wild Home ');    // false

The above is used to detect whether the string is composed of three characters, you can see the results may be more confused, why the second mismatch? The reason is "?? "in the Wild home"??? word, careful observation, you will find it is not "auspicious" in the word, but it's a special-shaped word, the word is also a Chinese character, but later in the Japanese is more common, for such a word, the general regular is difficult to match, and in ES6, we can specify a U modifier, enable Unicode mode, for greater than The Unicode characters of the \uffff are Matched. After we have added the U modifier, the regular match succeeds:

/^. {3}$/u.test ('??? Wild Home ');   // true

similarly, There are two other examples:

// the following regular contains Unicode characters and corresponding quantifiers /?? {3}/.test ('?????? ');     // false/?? {3}/u.test ('?????? ');    // true // The following is used to match a non-whitespace character /^\s$/.test ('?? ');         // false/^\s$/u.test ('?? ');        // true

In addition, ES6 new curly braces Unicode notation, like this:

var a = ' \u{20bb7} ';       // '?? ' /\u{20bb7}/u.test ('?? ');   // true

however, when using this expression, be very careful, because the \u in the normal regular in the match character u, and when the Unicode mode is turned on, it is not necessarily:

// detects if a 3 ' u ' character /\u{3}/.test (' UUU ') is included;      // true // detects if the character ' \u{3} '/\u{3}/u.test (' UUU ') is included;     // false/\u{3}/u.test (' \u{3} ');   // true

From the above results, when the Unicode mode is turned on, the \u and quantifier {3} form a Unicode character, so the result is completely different, in the actual development, pay special Attention.

After you finish speaking the U modifier, Let's talk about the new y modifier of ES6.

The Y modifier corresponds to the English full name is sticky, "sticky" meaning, indicating that the next match target must immediately follow the previous match, that is, multiple matches, each time the matching target must be in the starting position, the next match must be in the previous match succeeded in the last Position. The y-modifier is somewhat similar to the global g-modifier, but with a difference, let's look at the following example:

varSource = ' Hello-hello-world ';varRe1 =/hello/g;varRe2 =/hello/y;re1.exec (source); //["hello"]Re2.exec (source);//["hello"]Console.log (re2.lastindex);//6//a new round of matches will be made in "-hello-world"re1.exec (source); //["hello"]Re2.exec (source);//NULL

As you can see, the Re1 is g-modified, the Re2 is the y-modifier, the first round is the same, and we get the starting position of the next match through the Lastindex property of the regular instance, and we know that the next round will be matched in "-hello-world" because it is not "hello" at the start Position. , the result is that G still matches the success, and the Y match fails and returns Null.

Let's make a little change to the regular so that when the second match, "hello" is in the starting position to match it successfully:

var source = ' Hello-hello-world '; var re2 =/hello-/y;re2.exec (source);            // ["hello-"]  ///  6//  when a new round of matches will be re2.exec (source)            in "hello-world"; // ["hello-"]

We can also match the result by modifying the regular Lastindex property to change the index of the new round match starting position, so that it conforms to the rules of y, and also matches the Success:

var source = ' Hello-hello-world '; var re2 =/hello/y;re2.exec (source);            // ["hello"] // manual Change LastIndexre2.lastindex = 6; re2.exec (source);            // ["hello"]

From the above examples, the Y modifier requires that the match target must appear at the starting position, which implies the effect of the start tag "^":

/hello/y.test ('-hello ');    // false // equivalent to the following/^hello/.test ('-hello ');    // false

When Y and global G appear simultaneously, the global match will be limited, in addition to the Regex#exec () method described above, the Gy combination will also work on the replace and match two methods of string, the global match G plus y, the matching pattern is more strict, The target must appear in the first place at each match:

//string#replace ()' Hello-hello-world '. replace (/hello/g, ' Hey ');//"hey-hey-world"//plus y, The second hello will not be matched and replaced' Hello-hello-world '. replace (/hello/gy, ' Hey ');//"hey-hello-world"//it needs to be changed to the following .' Hello-hello-world '. replace (/hello-/gy, ' hey-');//"hey-hey-world"//String#match ()' Hello-hello-world '. match (/hello/g);//["hello", "hello"]' Hello-hello-world '. match (/hello/gy);//["hello"]' Hello-hello-world '. match (/hello-/gy);//["hello-", "hello-"]

The above is the full content of the regular modifier, in the next article the blogger will introduce meta-character related content, please look forward to.

Resources:

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Http://es6.ruanyifeng.com/#docs/regex

JavaScript series Article: detailed Jiu Zheng expression of the second

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.