Regular knowledge point interpretation and common expressions (judging valid numbers, mobile phone number, etc.)

Source: Internet
Author: User
Tags array example

---restore content starts---

1, the regular is only used to deal with strings: matching, capturing

Match: Verifies that the current string conforms to our rules (every regular is a rule) capture: In the entire string, the characters that match the rules are sequentially fetched to the--->exec, match, replace
2, the regular composition: meta-characters, modified OFDM characters: special meaning of metacharacters: \d match a 0-9 of the number equivalent to [0-9], and its opposite \d match an arbitrary character except 0-9 equivalent to ""  \w match a 0-9, A-Z, a-z_ number or character, equivalent to [ 0-9a-za-z_]  , \s match a white space character (space, Tab ...) \b Matches a word's boundary "w100 w000" \ t matches a tab \ n matches a newline. Match an arbitrary character except \ n ^ with a certain meta-character at the end of a meta-character \ Translate character x|y  x or y of one [xyz] x, y, z, any of [^xyz] In addition to X, Y, Z, any of the [a-z] ->   matches any one of the characters in A-Z [^a-z] ->  matches any one character in A-Z () in the regular group quantifier: *  0 to multiple +  1 to multiple?  0 to 1    ? In the regular meaning of more     placed after a non-quantifier meta-character represents the occurrence of 0-1 times   For example/^\d?$/appears 0-9 direct number 0 to 1 times     placed after a quantifier meta-character, cancel capture when the greed of the time   /^\d+?$/captures only the first captured number--->2    (?:) Group value matching does not capture     (? =) forward pre-check     (?!) Negative to pre-check () the role of 1) change the default priority 2) can be grouped to capture 3) group reference  {n} occurs n times {n,} appears n to many times {n,m} occurrences of N to M ordinary metacharacters any word regular in addition to the above have special meaning, The others are ordinary metacharacters that represent the meaning of themselves: I: Ignoring the case of letters M:multiline multi-line matching G:global global match    regular use in Project 1) Judging is the regular of valid numbers     Valid numbers are: positive, negative, 0, fractional the first part: May appear add or subtract or no second part: One number can be 0, multi-digit cannot start with 0 The third part: can have the decimal place can also have no decimal, but once appears the decimal point, after at least with a number var reg =/^[+-]? (\d| [1-9]\d+] (\.\d+) $/; valid positive integer (inclusive 0):/^[+]? (\d| [1-9]\d+) $/; valid negative integer (inclusive 0):/^-(\d|[ 1-9]\d+) $/;  Judge mobile phone number (simple version): Var  reg=/^1\d{10}$/;  determine the first part of the mailbox: numbers, letters, underscores,-one to many, Part two: @ Part Three: numbers, letters, one to many, Part IV: ( . Two to four-bit). com  . CN  . NET  .      .com.cnvar Reg =/^[0-9a-za-z_-][email protected][0-9a-za-z-]+ (\.[ a-za-z]{2,4}) {1,2}$/  judge the age between 18 and 65 18-19/20-59/60-65var  reg =/^ ((18|19) | ( [2-5]\d) | (6[0-5])) $/  Real and effective People's Republic of China 2-4 characters var reg = /^[\u4e00-\u9fa5]{2,4}$/;  ID number The top six is the province---City County (district) four-bit year two-month two-day simple version     var reg =/^\d{17} (\d| X) $/;    130828199012040617 Complex edition     var reg =/^ (\d{2}) (\d{4}) (\d{4}) (\d{2}) (?: \ D{2}) (\d) (?: \ d| X) The $/;   details Point [] any character appearing in it represents its own meaning, for example: [.] In the "." is to represent a decimal point instead of any character except \ n [] 18 is not the number 18 but 1 or 8, for example [18-65] is 1 or 8-6 or 5 in any one of the    1, the Exec regular capture method---> match first, And then capture the matched content if the string does not match this regular, the returned result of the capture is null if and regular match, the return result is an array example var str = "2015zhufeng2016peixun" var reg =/\d+/;  The first item is what we captured index: the index at which the captured content starts in the meta-string input: Captured raw string  2, regular captureEvery capture that is lazy is starting from the LastIndex value, the first time the capture, lastindex=0, starting from the original string index of 0 to find the capture, and by default, the first capture is complete, the value of LastIndex does not change, or 0, So the second capture starts with the original string index at 0 and finds the first capture   workaround: Add global modifier g---> Plus g, after the first capture is complete, the value of the lastindex changes, Becomes the start index of the first character after the first capture of the content, and the second capture is the ...  question to continue looking backwards: do not use the global modifier g to manually modify the Lastindex value after each capture is done? No, although the manual modification of the lastindex, it does change the value of the lastindex, but the regular search is still starting from index 0 var str =  "zhufeng2015peixun2016";     var reg = /\d+/g; example     to prevent a dead loop without the global modifier g, we add a g  to the manual without adding g before processing.    regexp.prototype.myexecall = function myexecall ()  {         var _this = this, str = arguments[0], ary  = [], res = null;        !_this.global  ?  _this = eval (_this.tostring ()  +  "G")  : null;         res = _this.exec (str);  &Nbsp;      while  (RES)  {             ary[ary.length] = res[0];             res = _this.exec (str);         }        return ary;    };     var ary = reg.myexecall (str);     console.log (ary);          console.log (Reg.lastindex);//->0         var res = reg.exec (str);         console.log (res);          console.log (Reg.lastindex);//->11         res = reg.exec (str);         console.log (res); &nbsP;        console.log (Reg.lastindex);//->21         res = reg.exec (str);         Console.log (res);//->null 3, match: There is a method called match in the capture string that can also be captured, and as long as we cancel the lazy nature of the regular, we can capture everything by executing the match method.     var str = "zhufeng2015peixun2016";    var reg =/\d+/g;    Console.log (Str.match (reg)); nbsp   Question: Well, how good are we to replace exec with match?     4, regular packet captures each capture, not only can capture the big regular match content, You can also capture the contents of each small group (Zhong) individually to         var str =  "zhufeng[2015]peixun[2016";         var reg = /\[(\d) (\d+) \]/g;         var res = reg.exec (str);         console.log (RES);        ["[]",  "2",  "015",  index: 7,  input:  "zhufeng[2015]PEIXUN[2016] "] The first item is the content captured by the large res[0] The second item is the content captured by the first group Res[1] The third item is the content captured by the second group Rex[2] .... Only matching of    groupings is not captured: if we do the matching of the grouped content but do not capture it, we just need to precede the grouping with the following: You can        var str = "zhufeng[2015" PEIXUN[2016] ";      var reg =/\[(?: \ d) (\d+) \]/g;      var res = reg.exec (str);      Console.log (res);      ["[201] 5] "," 015 "...]       The first item in the array is the content captured by the res[0]      The second item in the array is the content captured by the second group res[1]      The first group was added?: , so only match does not capture the difference between  5, exec, and match match can only catch large regular match content, for the group capture, is unable to get the packet matching content, so if the capture is not required to capture the grouped content, we directly with match more convenient, If we need to capture the grouped content, we can only use exec to capture var str =  "zhufeng[2015]peixun[2016";
var reg =/\[(\d+) \]/g;
Console.log (Str.match (reg));//->["[2015]", "[2016]"]
var ary = [];
var res = reg.exec (str);
while (res) {
Ary.push (Res[1]);
Ary.push (regexp.$1);//regexp.$1 gets the content captured by the current regular first group (may not be captured under some IE browsers)
res = reg.exec (str);
}
    console.log (ary);  6, regular greed: at the time of each capture, always follow the longest result of regular match capture     VAR STR  =  "zhufeng2015peixun2016";        var reg =  /\d+/g;        console.log (Reg.myexecall (str));//-->["2015", "2016"]     var str =  "zhufeng2015peixun2016";     var reg  = /\d+?/g;    console.log (Reg.myexecall (str));//-->["2",  "0",  "1",   "5",  "2",  "0",  "1",  "6"]  7, group reference \2 represents the content identical to the second grouping \1 represents the content var that appears and is identical to the first group  reg=/^ (\w) (\w) \2\1$/;    "Woow", "1221" ...    8, string method----> Replace: Replace a character in a string with a new content 1) If you do not use a regular, replace can only replace one of the strings, you need to substitute multiple var str =  that need to be executed more than once " zhufeng2015 zhufeng2016 ";    " Zhufeng " -> " Everest "     Str = str.replace ("Zhufeng", "Everest"). Replace ("Zhufeng",  "Everest");      there are times when it's not possible to replace      " Zhufeng " -> " Zhufengpeixun "    str = str.replace (" Zhufeng ", " Zhufengpeixun "). Replace (" Zhufeng ", " Zhufengpeixun ");      [the first parameter can be a regular]  Replace all matches with the regular match (however, as with the catch, the default is lazy, and only the global modifier G is allowed)         var str  =  "zhufeng2015 zhufeng2016";        str =  Str.replace (/zhufeng/g,  "Zhufengpeixun");         console.log (str) ;      1) execution and execution number of issues      in fact, the principle of exec capture is identical      For example, if we pass a function in the second argument, each time we capture the current function in a string, I take a total of two captures in the  ->, so the function executes two times     var  str =  "zhufeng2015 zhufeng2016";     str = str.replace (/zhufeng/g,  function  () &NBSp {     2) parameter issues       console.dir (arguments);      Not just perform function, And we passed the parameters to our function, and the arguments passed and the contents of each exec capture are identical       if the first exec capture->["Zhufeng", Index:0,input: "Raw string"]       Parameters inside the first execution function       arguments[0] ->  "Zhufeng"/**/      arguments[1] -> 0   equivalent to index  in Exec start capturing the index location       arguments[2] - >  "raw string"   equivalent to input      3 in exec) return value problem       Return what is returned, The equivalent of replacing the currently captured content with what       return  "Zhufengpeixun";     });     console.log (str);       fromEverest Training

---restore content ends---

Regular knowledge point interpretation and common expressions (judging valid numbers, mobile phone number, etc.)

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.