1. Regular expression basics

1.1 Creating regular expressions

1.1.1 Using a regular expression literal

const regex = /^[a-zA-Z]+[0-9]*\W? _$/gi;Copy the code

1.1.2 Calling the constructor of the RegExp object

const regex = new RegExp(pattern, [, flags])
Copy the code

1.1.3 Special Characters

- ^ Start of matching input - $End of matching input - * 0 or more {0,} - + 1 or more {1,} -? -0 or 1 {0,1}. - Used for prior assertion - if followed by any quantifier *, +,? Or after {} will make the quantifier non-greedy - using /\d+/ for "123abc" will return "123", - using /\d+? /, then only "1" will be matched. Matches any single character other than a newline - (x) matches 'x' and remembers matches - (? :x) matches 'x' but does not remember the match -x (? =y) matches 'x' only if 'x' is followed by 'y'. This is called forward positive lookup. - x(? ! Y) matches 'x' only if 'x' is not followed by 'y', this is called a positive negative lookup. - x | y match 'x' or 'y'. - {n} repeat n times - {n, m} match at least n times and up to m times - [xyz] stands for X or Y or z - [^xyz] is not x or Y or Z - \d numeric - \d non-numeric - \ S Whitespace, including Spaces, tabs, page feeds, and newlines. - \S Non-blank characters - \W Word characters (letters, digits, or underscores) [A-zA-Z0-9_] - \W Non-single-character characters. [^ A Za - z0-9 _] \ 3 said the third grouping - \ b word boundaries - / \ bm/match "moon" in the "m"; - \B Non-word boundaryCopy the code

1.2 Using regular expressions

  • Exec a RegExp method that performs a lookup match in a string, returning an array (null if no match is found).
  • Test A RegExp method that tests a match in a string, returning true or false.
  • Match A String method that performs a search for a match in a String, returning either an array or null if there is no match.
  • Search A String method that tests a match in a String, returning the index of the matched position, or -1 on failure.
  • Replace A String method that looks for a match in a String and replaces the matched substring with a replacement String.
  • Split a String using a regular expression or a fixed String, and stores the delimited substrings into an array of String methods.

1.2.1 Three methods of regular objects

        //1.test() checks whether a string is present in the string and returns a Boolean value
        var re = /abc/;
        var str = '00abc66';
        console.log(re.test(str));  // true
        //2.exec() finds and returns a string specified in the string, matching only once
        var re = /abc/;
        var str = 'a0bc88abc00abc';
        console.log(re.exec(str));  // ["abc", index: 6, input: "a0bc88abc00abc", groups: undefined]
        The compile() method is used to change the content of the match
        var re = /ab/;
        var str = "aabcdef";
        console.log(re.test(str));  //true
        re.compile(/bd/);
        console.log(re.test(str));  //false
        re.compile('66');
        console.log(re.test(str));  //false
Copy the code

1.2.2 Reged-related methods in strings

        //1.search() method, which returns the position (subscript) of the first occurrence of the qualified string
        var re = /abc/;
        var str = '00abc66';
        console.log(str.search(re));        / / 2
        //2. The match() method returns the result of the search, or NULL if not found
        console.log(str.match(re));         // ["abc", index: 2, input: "00abc66", groups: undefined]
        //3.replace() method, which replaces the matched content with the specified content
        console.log(str.replace(re, "*"));
        //④split() to split a string into an array of strings
        console.log(str.split(re));
Copy the code

1.3 Regular expression expressions are related

1.3.1 Subexpression

In regular expressions, the content enclosed by a pair of parentheses is called a subexpression. Var re = /\d(\d)\d/;

1.3.2 capture

In a regular expression, when a subexpression matches a corresponding content, the system automatically captures the behavior and puts the matched content into the system cache. We call this process capture.

1.3.3 Backreferencing

In regular expressions, we can use \n (n>0, a positive integer, representing the buffer number in the system) to retrieve the contents of the buffer. This process is called “backreferencing”.

    var str = "d1122jj7667h6868s9999";
    // find the number of type AABB
    console.log(str.match(/(\d)\1(\d)\2/)); / / 1122
    // Find the number of type ABBA
    console.log(str.match(/(\d)(\d)\2\1/)); / / 7667
    // Find the number of type ABAB
    console.log(str.match(/(\d)(\d)\1\2/)); / / 6868
    // Find four consecutive identical numbers
    console.log(str.match(/(\d)\1\1\1/));   / / 9999
Copy the code

1.4 qualifiers

Qualifiers specify how many times a given character in a regular expression must occur to satisfy a match.

* : matches the previous subexpression zero or more times, 0 to more + : matches the previous subexpression one or more times, 1 to more? : matches the preceding subexpression zero or once, 0 or 1 {n} : matches the specified n times. {n,} : matches at least n times. {n,m} : matches at least n times and at most m timesCopy the code

Note: for {n,m}, when the re matches a string of multiple times, the match with more times is preferred, that is, it will not match n times if it can match m times. This is greedy mode (default).

If you add? That is {n, m}? Is changed to non-greedy mode (lazy mode), then the re matches n times first.

    var str = "aa1a22a333a6a8a";
    console.log(str.match(/a\d*/));      //a
    console.log(str.match(/a\d+/));      //a1
    console.log(str.match(/a\d? /));      //a
    console.log(str.match(/a\d{3}/));    //a333
    console.log(str.match(/a\d{2,}/));   //a22
    console.log(str.match(/ / a \ d {1, 3}));  //a1
    console.log(str.match(/ a \ d {1, 3}? /)); //a1

    // The greedy model can be used as follows:
    // Greedy mode starts with 'a2 ', but returns 'a22'
    // Note: it is a string that meets multiple degree conditions at the same time
    var str = "a22aa1a333a6a8a";
    console.log(str.match(/ / a \ d {1, 3}));   //a22
    console.log(str.match(/ a \ d {1, 3} / g));  //a22 a1 a333 a6 a8
    console.log(str.match(/ a \ d {1, 3}? /));  //a2
    console.log(str.match(/ a \ d {1, 3}? /g)); //a2 a1 a3 a6 a8
Copy the code

1.5 locator

A locator can fix a regular expression at the beginning or end of a line. You can also create regular expressions that appear only within a word or at the beginning or end of a word.

^ (out-of-character) : matches the start of the input string. $: matches the end of the input stringCopy the code

1.6 Matching Patterns of Regular Expressions (Modifiers)

Additional rules representing regular matches, placed at the end of the regular pattern. Modifiers can be used singly or together.

  • 1. G global matches, finding all matches instead of stopping after the first match

  • 2. I Matches all cases

  • 3. M multiple lines, treat the beginning and ending characters (^ and $) as if they work on multiple lines (that is, match the beginning and end of each line respectively (split by \n or \r), not just the beginning and end of the entire input string.

  • 4. S is the opposite of m

   var re = /^[a-z]/gim;   // Can be used in combination
Copy the code

1.7 Escape Characters

Because. + \ and so on are part of regular expressions, they sometimes need to be matched, so you need to escape special characters with backslashes.

Character to escape: dot. Parentheses () brackets [] right/left slash slash \ select clause | *? {} + $^Copy the code

2. Regular exercises

2.1 Match the number at the end

/\d+$/g

2.2 Counting the Number of Spaces

If there are Spaces in the string but the number of Spaces may be inconsistent, use the re to unify the number of Spaces into one.

let reg = /\s+/g
str.replace(reg, "");
Copy the code

2.4 Phone Number is regular

  • The area code must contain 3-4 digits
  • Use a hyphen (-) after the area code to connect the 7-8 digits of the phone number
  • The extension number is a 3- to 4-digit number. This parameter is optional, but the extension number can be connected with a hyphen (-)
/^\d{3.4}-\d{7.8}(-\d{3.4})? $/Copy the code

2.5 Mobile Phone Number Regular Expression

Regular verification mobile phone number, ignore the front 0, 130-139, 150-159 support. I’m going to ignore the 0 and say it’s 11 bits.

/^0*1(3|5)\d{9}$/

2.6 Deleting whitespace from a String using regular expressions

funtion trim(str) {
  let reg = /^\s+|\s+$/g
  return str.replace(reg, ' ');
}
Copy the code

2.7 Restrict text boxes to only numbers and two decimal points, etc

/ ^ \ d * \ \ d {0, 2} $/

2.8 Enter only lowercase letters, decimal points, colons, and forward and backward slashes (:./).

/^[a-z\.:\/\\]*$/

2.9 Replace the content before the decimal point with the specified content

For example: infomarket. PHP? Id =197 instead of test.php? id=197

var reg = + / / ^ [^ \];
var target = '-- -- -- -- -- -- -- -- --';
str = str.replace(reg, target)
Copy the code

2.10 Matches only Chinese regular expressions

/[\u4E00-\u9FA5\uf900-\ufa2d]/ig
Copy the code

2.11 Returns the number of Chinese characters in a string

Remove the non-Chinese characters and return the length attribute.

function cLength(str){
  var reg = /[^\u4E00-\u9FA5\uf900-\ufa2d]/g;
  // Matches non-Chinese regular expressions
  var temp = str.replace(reg,' ');
  return temp.length;
}
Copy the code

2.12 Matching the first three IP addresses using regular Expressions

Just match the last paragraph and replace it with an empty string

function getPreThrstr(str) {
  let reg = /. \ d {1, 3} $/;
  return str.replace(reg,' ');
}
Copy the code

2.13 matchulContent between tags

/<ul>[\s\S]+? </ul>/i

2.14 Obtaining the file name using a regular expression

c:\images\tupian\006.jpg

It may be directly in the root directory of the disk, or it may be in several layers of directories, requiring only the file name to be replaced. Matches zero or more characters that are not left and right slashes first, and then one or more left and right slashes.

function getFileName(str){
  var reg = /[^\/]*[\/]+/g;
  // XXX \ or XXX /
  str = str.replace(reg,' ');
  return str;
}
Copy the code

2.15 Absolute Path is disguised as pair path

“Http://23.123.22.12/image/somepic.gif” to: “/ image/somepic. GIF”

var reg = /http:// [^ /] + /;
str = str.replace(reg,"");
Copy the code

2.16 The user name is regular

For user name registration, the user name can contain only Chinese, English, digits, underscores (_), and 4-16 characters.

/ ^ [\ u4E00 \ u9FA5 \ uf900 - \ ufa2d \ w] $/ dec {4}Copy the code

2.17 Matching English Addresses

The rules are as follows: contains “dots “,” letters “,” Spaces “,” commas “, and” digits “, but cannot begin or end with any character other than letters.

/^[a-zA-Z][.a-zA-Z,0-9]*[a-zA-Z]$/
Copy the code

2.18 Re matches the price

A number of leading digits, possibly with a decimal point, followed by two digits.

/^\d+(.\d{2})? $/Copy the code

2.19 Matching of ID card numbers

The ID number can be 15 or 18 digits, with the last digit being an X. Everything else is just numbers

/^(\d{14}|\d{17})(X|x)$/
Copy the code

2.20 Capitalize the first letter of a word

Capitalize the first word of each word, lower case the rest. For example, blue Idea is converted to Blue Idea, and blue Idea is also converted to Blue Idea

function firstCharUpper(str) {
  str = str.toLowerCase();
  let reg = /\b(\w)/g;
  return str.replace(reg, m= > m.toUpperCase());
}
Copy the code

2.21 Regexing the date format

Yyyy-mm-dd format, four digits, line, one or two digits, line, and then one or two digits.

/^\d{4}-\d{1.2}-\d{1.2} $/Copy the code

2.22 Deleting file name extensions

www.abc.com/dc/fda.asp 变为 www.abc.com/dc/fda

function removeExp(str) {
  return str.replace(/.\w$/.' ')}Copy the code

2.23 Verifying the Mailbox Regular expression

It must start with one or more word characters or -, plus at sign, and then one or more word characters or -. And then click “.” And the word character and -, can have one or more combinations.

/^[\w-]+@\w+.\w+$/
Copy the code

2.24 Regis determines whether the label is closed

Tags can be closed in two ways, closed or symmetric.

/<([a-z]+)(\s*\w*? \s*=\s*". +?")*(\s*? >[\s\S]*? (</\1>)+|\s*/>)/i
Copy the code

2.25 Determines whether the value is a combination of letters and digits

The value must be a combination of letters and digits and cannot be smaller than 12 characters

/^(([a-z]+[0-9] +) | ([0-9]+[a-z]+))[a-z0-9]*$/i
Copy the code

2.26 Replace Arabic numerals with Uppercase Chinese characters

function replaceReg(reg,str){
  let arr=["Zero"."One"."贰"."叁"."Boss"."Wu"."Lu"."Pure".""."Nine"];
  let reg = /\d/g;
  return str.replace(reg,function(m){return arr[m];})
}
Copy the code

2.27 Remove all attributes of the label

<td style="width: 23px; height: 26px;" align="left">* * *</td>It becomes without any properties<td>* * *</td>
Copy the code

Instead of capturing a matching attribute, capture a matching tag and replace the string with the result. The re is as follows:

/ (
       
        )
       )\s(?>Copy the code

2.28 Hump indicates

String.prototype.camelCase = function () {
        / /. *? Non-greedy matching, dot can match any character, asterisk is 0 to N characters match, question mark is 0 to 1;
        // (^\w{1}): matches the first initial letter
        // (.*) : matches the first character of any character. The. Represents any character

        // -param 1: the matched string
        // -param 2: matched substring
        // -param 3: matching substring
        // - Param position
        // -param 5: original string 4: the matched string is in the string

        return this.replace(/(^\w{1})(.*)/g.function (match, g1, g2) {
            return g1.toUpperCase() + g2.toLowerCase();
        });
    }
Copy the code

2.29 Template Character String

// str = 'name: @(name), age:@(age)'
       // data = {name : 'xiugang', age : 18}
       /** * implement a simple data binding *@param str
        * @param data
        * @return {*}* /
       String.prototype.formateString = function (data) {
           return this.replace(/@((\w+))/g.function (match, key) {
               // Note that the value found here must be returned (if undefined, no data).
               // note that the typeof a value is undefined, which can be determined by typeof
               console.log(typeof data[key] === 'undefined');
               return data[key] === 'undefined' ? ' ' : data[key];
           });

       }
Copy the code

2.30 Remove the Spaces on both sides

/** * remove the Spaces * on both sides@param str
        * @return {*}* /
       String.prototype.trim = function () {
           return this.replace(/(^\s*)|(\s*$)/g.' ');
       }
Copy the code

2.31 Get URL parameters: Use replace to save to an array, and then retrieve the data from the array

'http://www.189dg.com/ajax/sms_query.ashx?undefined&undefined&undefined-06-27&undefined-06-27'
 url.replace(/(\w+)=(\w+)/g.function(a, b, c){
   console.log(a, b, c)
 })
action=smsdetail action smsdetail
sid=22 sid 22
stime=2014 stime 2014
etime=2014 etime 2014


// Encapsulate as a function
var url = "Http://127.0.0.1/e/action/ShowInfo.php? classid=9&id=2";
function parse_url(_url){
 var pattern = /(\w+)=(\w+)/ig;
 var parames = {};
 url.replace(pattern, function(a, b, c){
   parames[b] = c;
 });
 return parames;
}
var parames = parse_url(url);
alert(parames['classid'] + "," + parames['id']);
Copy the code