The definition of JS small knowledge Regular expression

Source: Internet
Author: User

There are two ways to define regular expressions in JS: normal way, constructor mode

The regular object is the built-in object of JS

The properties of the regular

The regular method

The method of string in JS

One, ordinary way (double slash//mode): var reg =/Expression/Additional parameters

The expression is placed in a double slash "//" and the expression is a string that can use special characters

Additional parameters placed in the second slash "/" after the second, is used to extend the meaning of the expression, there are three main parameters: G,i,m;g can be configured globally, I represent the case-insensitive configuration, M can be multi-line configuration, these three parameters can be any combination or no parameters;

For example:

var reg=/a*b/;
var reg=/abc+f/g; Abc+f is an additional parameter for the expression G

Second, the constructor: Var reg=new RegExp ("expression", "additional parameters");

For example:

   var reg=new RegExp ("a*b");
var reg=new RegExp ("Abc+f", "G");

Three, the difference between the ordinary way and the way of the structure function

  The expression in the normal way must be a constant string, and the expression in the constructor can be a constant string, or it can be a JS variable

For example:

var reg = new RegExp ("^ (?:( [1-"+ flag +"]) (?!. *\\1.*$)) +$ "," Gim ");//falg is a variable

Four, the regular object and its properties

The regular object is a built-in object in JS, like array and math, without the need for third-party library support;

  

You can see that it has the global property, which is a Boolean type that indicates whether the regular is a global match, a ignorecase property, a Boolean type that indicates whether the case is ignored, lastindex is the number type, and is used to indicate where the last match succeeded. Multiline, a Boolean type that is used to indicate whether a multiline match, source,string type, is used to represent the contents of the regular.

Methods of regular expressions

Generally, for a regular object, there are basically three methods that we can use, namely regobj.test,regobj.exec and Regobj.compile

1) The test method, which is used to test whether a string matches a regular match, returns True, or false.

The method takes a string as a parameter

Code:

var reg=/boy (s)? \s+and\s+girl (s)?/gi; Console.log (Reg.test (' Boy    and   Girl '));

The result prints true on the console. This method is also one of the most common methods.

2) Compile method

The function of this method is to be able to compile the regular expression, the compiled regular in use when the efficiency is higher, suitable for a regular number of calls, if only one or two times for a regular, then the method has no particularly significant effect.

The accepted parameter is also a regular.

Code:

    var reg=/[abc]/gi;    Console.log (Reg.test (' a '));    Reg=/[cde]/gi;    Console.log (Reg.test (' a '));    Reg.compile (reg);    Console.log (Reg.test (' a '));

Results:

There is no difference between the compiled regular and the non-compiled regular results, but the efficiency of multiple invocations is higher.

3) Exec method

This method belongs to a more complex method, it takes a string, returns an array, the No. 0 element in the array is a matching substring, the second element is the result of the first subgroup match in the regular (if there is a subgroup, that is, in the regular parentheses in the grouping), The third one is the result of the second subgroup match in the regular (if there is a second sub-group) ... And so on, if there is no regular sub-group, then the array length is only 1, which is the substring that matches. At the same time, the returned array is also an object that has two properties, the index representing the position of the substring currently matched to, and the input property representing the original string being matched. Finally, if the regular object in the method is not a global match, that is, there is no G modifier, each call will only match the first result at the beginning of the string, and the result will be the same each time it is called. Only the global match can be specified to match from left to right, each call matches one result, the Lastindex property of the regular object advances to the end of the match, and the next time it is called, the match starts at lastindex and not from the beginning.

Global Match Code:

   var reg=/(\w) L (\w)/g;   var str= "Hello World Hello 123 Hello programmer hello Test";   var arr=reg.exec (str);    while (arr) {        console.dir (arr);        Console.log ("LastIndex:" +reg.lastindex);        Arr=reg.exec (str);    }

The results are as follows:

Non-global matching code:

   var reg=/(\w) L (\w)/;   var str= "Hello World Hello 123 Hello programmer hello Test";   var arr=reg.exec (str);   var i=0;    while (arr) {        i++;        if (i<=4) {        console.dir (arr);        Console.log ("LastIndex:" +reg.lastindex);        Arr=reg.exec (str);        }        else{break            ;        }    }

In order to prevent an infinite output, only the first 5 results are output, as follows:

This time the result of each invocation is the same, lastindex has not changed at all.

The method of string in JS

1) Search method

The method is a method of a string object that finds the position of the first matched substring, returns the index value of a number type if found, otherwise returns 1, which returns only the position of the first match.

It takes a regular or substring as a parameter, here we only discuss the situation of the regular.

Code:

    var str= "Hello World";    Console.log (Str.search (/o/g));

The output is 4, and you can see that although there are multiple matching results and are declared as global matches, the position of the first matched substring is returned;

2) Replace method

The method is used to replace some substrings in a string with the required content, accept two parameters, the first parameter can be a regular or substring, the match needs to be replaced, the second parameter is replaced by the new substring. If the declaration is a global match, all results are replaced, or only the first match to the result is replaced.

The code is as follows:

    var str= "Hello World,hello test";    Console.log (Str.replace (/hello/g, ' Hi '));

The result is Hi World,hi test

If you remove the G modifier from the above code, the result of the return is Hi World,hello test

3) Split method

This method is mainly used to split a string into an array, it takes a regular or a substring (string) as a parameter, returns an array, in simple case, we do not need to use the regular, only if the string splitting rule is not uniform in the case of the need to use the regular, as follows:

    var str= "How|old*are you    ";    var arr=str.split (/\| | \*|\s+/);    Console.log (arr);

Here we need to split Str into a word array, because there is a different delimiter between each word, we take the regular to match, the result is as follows:

4) Match method

The method takes a regular parameter to match a string whose output is consistent with the result of the Exec method, which is not a global match, which is an array with an additional property, and if a global match is taken, returns no information related to its matched string, returning only the result of the match.

Non-global matching code:

    var reg2=/(\w) s (\w)/;    var str2= "WS1ESR";    var result=str2.match (REG2);    var i=0;  while (result) {      i++;      if (i<=4) {      console.dir (result);      Console.log ("LastIndex:" +reg2.lastindex);      }      else{break        ;      }  }

The results are as follows:

For non-global matches, the result is exactly the same as the exec non-global match method returns.

Global Match Code:

    var reg3=/(\w) s (\w)/g;    var str4= "WS1ESTQSA";    Console.dir (Str4.match (REG3));

The results are as follows:

As you can see, it differs from the Exec method at the time of the global match, it returns all matching results as an array at once, and the array has no other attributes to point to the information that is matched to the string, and the Exec method returns an array of results each time it is returned by the global match. And this array contains only this match information, but also has the information that points to the matched string, that is, the match method returns all the matching results one time under the global match, and the exec returns in the global match is still the result of the match.

Seven, the regular verification Daquan link http://www.cnblogs.com/zxin/archive/2013/01/26/2877765.html

The definition of JS small knowledge Regular expression

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.