Proficient in regular expressions (JavaScript)

Source: Internet
Author: User
Tags first string expression engine

In the previous article, I learned about the Regular Expression Engine and Its Matching Principle, next we will use the JS language in detail.

In JS, it is often used for string processing, form verification, Dom model processing, pure programming logic, and so on. In JS, regular expressions are used in two ways: Normal Mode and constructor mode.

  Normal Mode

Common method: var Reg =/expression/additional parameter
Expression: a string that represents a rule. special characters can be used to represent special rules.
Additional parameters: used to extend the meaning of the expression. Currently, there are three main parameters:
G: indicates that global matching can be performed.
I: It indicates case-insensitive matching.
M: indicates that multiple rows can be matched.
The above three parameters can be combined at any time, indicating that they are consistent with the meaning. Of course, they can also be left blank.
For example:
VaR reg1 =/[0-9] * B /;
VaR reg2 =/[A-Z] + F/g;
VaR reg3 =/^ [A-Z]/I;
VaR reg4 =/^ [A-Z]/GM;

  Constructor Method 

Constructor mode: var Reg = new Regexp ("expression", "additional parameter ");
The expressions and additional parameters are the same as normal expressions.
For example, VAR reg1 = new Regexp ("A | B ");
VaR reg2 = new Regexp ("[A-Z] $", "I ");

A normal expression must be a constant string, and an expression in the constructor can be a constant string or a JS variable. For example:
VaR value = "ABC ";
VaR Reg = new Regexp (value, "I ");

The following are other metacharacters of javascript:

  1. Expression operation

  1.1 Exec

Exec (STR) returns the first string in STR that matches the expression and is represented in an array. Of course, if the expression contains parentheses for capturing, the returned array may also contain matching strings in (), for example:
VaR regx =/\ D + /;
VaR rs1_regx.exe C ("3432ddf53 ");
The returned RS value is {3432}
VaR regx2 = new Regexp ("AB (\ D +) C ");
VaR rs2jwregx2.exe C ("ab234c44 ");
The returned RS value is {ab234c, 234}

In addition, if there are multiple suitable matches, the first matching is returned for the first execution of exec. If the first matching is continued, the second and third matching are returned in sequence. For example:
VaR regx =/user \ D/g;
VaR rs1_regx.exe C ("ddduser1dsfuser2dd ");
VaR rs1=regx.exe C ("ddduser1dsfuser2dd ");
The RS value is {user1} and the RS value is {user2}. Of course, note that the G parameter in regx is required. Otherwise, the first match is returned no matter how many times exec is executed.

View code

  1.2 Test 

Test (STR) to determine whether the string 'str' matches the expression. A boolean value is returned. For example:
VaR regx =/user \ D +/g;
VaR flag = regx. Test ("user12dd ");
The flag value is true.

View code

            var reg=/user\d+/g;            var result1=reg.test("uuser12f");            var result2=reg.test("user");            document.write(result1+" "+result2);

  1.3 match 

Match (expr) returns an array of strings that match expr. If the parameter G is not added, the first match is returned. If the parameter G is added, all matching examples are returned:
VaR regx =/user \ D/g;
VaR STR = "user13userddduser345 ";
VaR rs = Str. Match (regx );
RS value: {user1, user3}

View code

            var reg1=/user\d+/;            var reg2=/user\d+/g;            var str="user12uerdduser33";            var result1=str.match(reg1);            var result2=str.match(reg2);            document.write(result1+" "+result2);

  1.4 search 

Search (expr) returns the first matched index value in the string that matches expr. Example:
VaR regx =/user \ D/g;
VaR STR = "user13userddduser345"; var rs = Str. Search (regx );
The RS value is 0.

View code

            var reg1=/user\d+/g;            var str="yyuser12uerdduser33";            var result1=str.search(reg1);            document.write(result1);

  1.5 replace 

Replace (expr, STR), replace the part matching expr in the string with Str. In addition, in the replace method, STR can contain a variable symbol $, in the format of $ N, representing the matching string of the nth to be remembered in the match (note that parentheses can be used for memory matching ). Example 1:
VaR regx =/user \ D/g;
VaR STR = "user13userddduser345 ";
VaR rs = Str. Replace (regx, "00 ");
RS value: 003userddd0045

Example 2:
VaR regx =/U (SE) r \ D/g;
VaR STR = "user13userddduser345"; var rs = Str. Replace (regx, "$1 ");
RS value: se3userdddse45

Pay special attention to the Replace (expr, STR) method. If expr is an expression object, it will be replaced globally (in this case, the expression must be appended with the parameter G, otherwise, only the first match is replaced. If expr is a string object, only the first matched part is replaced. For example:
VaR regx = "user ";
VaR STR = "user13userddduser345 ";
VaR rs = Str. Replace (regx, "00 ");
RS value: 0013userddduser345

View code

            var reg=/(user)\d+/g;            var str="yyuser12uerdduser33";            var result=str.replace(reg,"$1"+"007");            document.write(result);

The Replace (expr, STR) method is also important. Here, STR can be a string or function. Let's take an example:

View code

        function init()        {            var reg=/(use)(r)\d+/g;            var str="yyuser12uerdduser33";            var result=str.replace(reg,replaceFunction);            document.write(result);        }        function replaceFunction()        {            var args=arguments;            return args[0];        }

You can debug it and find that the arguments Dimension Array (not an array in a strict sense) is as follows:

  

The first element is the successfully matched string, and the last element is the complete string to be matched, the second-to-last position indicates the successful match (the first letter of a string is in front of the first letter, the second is between 0th letters and 1st letters, and so on ), the number in the middle will change to the right, representing the data recorded in your regular expression, that is, the information in parentheses (). Here I have (use) and (r ), so it exactly corresponds.

In fact, when the parameter is a function, it means that the Regular Expression Engine opens part of the matching process, so that we can control some operations. The purpose of this method is to capture the status when the engine matches successfully, then open all the data through arguments, and some users define whether to replace the matched data with other data. In my code, return is the first element, that is, the final result will not change, and because my expression uses g (Global match), you will find that you will enter this function for the second time, the second match is user33. As a result, we can find the powerful function when the parameter is a function. We can capture every state in which the engine matches successfully, and modify the information that matches successfully to what we want. It is more flexible than passing string parameters. You can set your own parameters for the method. anyone familiar with the JS syntax knows that your function has several parameters, which must correspond to the data in arguments at a time.

  1.6 split 

Split (expr): splits the string by matching the expr part, returns an array, and the result is the same if the expression is attached with the parameter G. Example:
VaR regx =/user \ D/g;
VaR STR = "user13userddduser345 ";
VaR rs = Str. Split (regx );
RS value: {3 userddd, 45}

View code

            var reg=/user\d/g;            var str="yyuser12uerdduser33";            var result=str.split(reg);            document.write(result);

  2. expression-related attributes

  2.1 lastindex  

Lastindex: returns the start position of the next match. Note that the lastindex will return the next matching value continuously only when it must be a global match (with the G parameter in the expression, otherwise, this value always returns the first matching position, for example, VAR regx =/user \ D /;
VaR rs1_regx.exe C ("sdsfuser1dfsfuser2 ");
VaR lastindex1 = regx. lastindex; rs1_regx.exe C ("sdsfuser1dfsfuser2 ");
VaR lastindex2 = regx. lastindex; rs1_regx.exe C ("sdsfuser1dfsfuser2 ");
VaR lastindex3 = regx. lastindex;
The preceding lastindex1 is 0, the second lastindex2 is 0, and the third is 0. If regx =/user \ D/g, the first is 9, and the second is 18, the third is 0.

View code

            var regx=/user\d/g;            var rs=regx.exec("sdsfuser1dfsfuser2");            var lastIndex1=regx.lastIndex;            rs=regx.exec("sdsfuser1dfsfuser2");            var lastIndex2=regx.lastIndex;            rs=regx.exec("sdsfuser1dfsfuser2");            var lastIndex3=regx.lastIndex;            document.write(lastIndex1+" "+lastIndex2+" "+lastIndex3);

  2.2 Source 

Source, returns the expression string itself. For example:
VaR regx =/user \ D /;
VaR rs1_regx.exe C ("sdsfuser1dfsfuser2 ");
VaR source = regx. source;
The source value is user \ D.

  2.3 Index  

Index, returns the current matched position. For example:
VaR regx =/user \ D /;
VaR rs1_regx.exe C ("sdsfuser1dfsfuser2 ");
VaR index1 = Rs. Index; rsw.regx.exe C ("sdsfuser1dfsfuser2 ");
VaR index2 = Rs. index;
Rsw.regx.exe C ("sdsfuser1dfsfuser2 ");
VaR index3 = Rs. index;
Index1 is 4, index2 is 4, and index3 is 4. If the expression is added with the parameter g, index1 is 4, index2 is 13, and index3 reports an error (index is empty or not an object ).

  2.4 Input

Input, used to match strings. For example:
VaR regx =/user \ D /;
VaR rs1_regx.exe C ("sdsfuser1dfsfuser2 ");
VaR input = Rs. input;
The input value is sdsfuser1dfsfuser2.

  2.5 [0]

[0], returns the first matching value in the matching result. For match, a number with multiple values may be returned, except for [0, [1], [2], and so on. For example:
VaR regx =/user \ D/g;
VaR rs1_regx.exe C ("sdsfuser1dfsfuser2"); var value1 = Rs [0]; rs1_regx.exe C ("sdsfuser1dfsfuser2 ");
VaR value2 = Rs [0];
The value of value1 is user1, and the value of value2 is user2

  3. Practice

  3.1  

Convert the following string to the corresponding string: (one interview question from our company)
T0.supermap.com/tiles/4/3/2.png
T4.supermap.com/tiles/m4/4/3.jpg
A7.supermap.com/tiles/5/m4/6.png
Convert to the corresponding
M0.iclient.com/tiles.png? X = 4 & Y = 3 & Z = 2
M4.iclient.com/tiles.jpg? X = M4 & Y = 4 & Z = 3
M7.iclient.com/tiles.png? X = 5 & Y = M4 & Z = 6

Answer (more than one ):

View code

            var regx=/^[a-z]([0-9]\.)supermap(\.com\/tiles)\/([a-z0-9]+)\/([a-z0-9]+)\/([a-z0-9]+)\.(png|jpg)$/;            var str1="t0.supermap.com/tiles/4/3/2.png";            var str2="t4.supermap.com/tiles/m4/4/3.jpg";            var str3="a7.supermap.com/tiles/5/m4/6.png";            var str="m"+"$1"+"iclient"+"$2"+"."+"$6"+"?x="+"$3"+"&y="+"$4"+"&z="+"$5";            var result1=str1.replace(regx,str);            var result2=str2.replace(regx,str);            var result3=str3.replace(regx,str);            document.write(result1+" "+result2+" "+result3);

Another answer is the suggestion from a friend who replies:

View code

  3.2

A friend asked a question in the group a few days ago: "[{chk: '-15-13-2-5-'}, {chk: '-1-13-4-5-2-'}, {chk: for long string data such as '-1-2-5-'}] ", you have selected several strings such as"-5-"and"-2, you want to obtain "{chk :'... '} ", which must contain all the options selected by the user. If you select "-5-" and "-4-" on the interface, only {chk: '-1-13-4-5-2-'} meets the conditions.

Answer:

View code

// This array is a combination of options selected on the user interface. It cannot be empty var strarray = ["-5-", "-4-"]; var STR = ""; // combine some regular expressions. Here, the expression combination is obtained as long as it contains elements in the array (VAR I = 0; I <strarray. length; I ++) {If (strarray. length = 1) {STR = strarray [0];} else {if (I = 0) {STR + = "(?: "+ Strarray [0];} else if (I = strarray. length-1) {STR + = "|" + strarray [I] + ")";} else {STR + = "|" + strarray [I] ;}} // Complete Combination expression STR = "(\ {chk: '[-\ D] *" + STR + "[-\ D] *' \}) "; // user string data var mydata =" [{chk: '-15-13-2-5-'}, {chk: '-1-13-4-5-2-'}, {chk: '-1-2-5-'}] "; var rexg = new Regexp (STR," G "); // return all data var array = mydata that contains the conditions selected by the user. match (rexg); var arraylast = []; var COUNT = 0; // cyclically traverse, extract data that meets all the conditions selected by the user for (var j = 0; j <Array. length; j ++) {for (var k = 0; k <strarray. length; k ++) {var Re = new Regexp ("(\ {chk: '[-\ D] * "+ strarray [k] +" [-\ D] *' \}) "," G "); If (! Re. test (array [J]) {break;} else {If (k = strarray. length-1) {arraylast [count ++] = array [J] ;}}} alert (arraylast );

I hope it will help you!

 

 

 

 

Related Article

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.