1. The following mind map summarizes all the contents of regular expression, regular expression creation, regular expression writing and common methods

2. What are regular expressions

Regular expressions are also called regular expressions. Regular Expression (often abbreviated as regex, regexp, or RE in code) is a logical formula for manipulating strings. It is a “Regular string” composed of predefined characters or a combination of these characters. Rules of the “string” is the expression of string filtering logic, given a regular expression and a string, we can use regular expressions to filter we want to be part of the string, or to determine a specific string, such as login registration input box prompts the password length must be 8 or must begin with a letter (as shown in figure 1), We can also perform all types of text search, text replace, and so on through regular expressions. You’ve probably heard or used regular expressions a lot, both in school and at work. I’ll use the RE abbreviation for regular expressions to simplify reading.

3. Regular expression features

1) Regular expressions are very logical, functional and flexible, and can quickly achieve complex control over strings in a very simple way

2) Due to the powerful functions of regular expressions, the application scenarios and scope are very wide

3) For those who are new to regular expressions, it is difficult to understand or use them, and the syntax is obscure, requiring patience and practice

4) The code readability of regular expressions is poor and requires a solid foundation to be accurately and quickly understood

5) Regular expressions are mainly text-oriented and can be used in various editors (such as Ctrl+F to open the text search box can also use regular expressions)

4. Regular expression creation in JavaScript

4.1 Created by the RegExp constructor of the regular object

<script>
    let re = new RegExp("Regular expression");
</script>
Copy the code

4.2 Create regular expressions between slashes

<script>
    let re = / Regular expression /;
</script>
Copy the code

5. Symbolic meaning in regular expressions

Regular expressions are composed of some normal characters and some metacharacters. Ordinary characters include uppercase and lowercase letters and numbers, while metacharacters have special meanings. Understanding metacharacters correctly is the most important thing to really use regular expressions well. The following table lists the metacharacters and their corresponding functions.

5.1 Regular expression modifiers

Modifiers can be used for more global searches that are case-insensitive:

The modifier describe
i Performs case-insensitive matching
g Perform global matches (find all matches instead of stopping after finding the first match)
m Perform multi-line matching

5.2 Regular expression Mode

Square brackets are used to find characters in a range:

expression describe
[abc] Find any character between square brackets
[0-9] Find any number from 0 to 9
(x l y) Find any options separated by l

Metacharacters are characters that have special meanings:

metacharacters describe
\ Returns the next character marker, or a backreference, or an octal escape
^ Matches the beginning of the input line
$ Matches the end of the input line
{n} Match certain n times
{n,} At least n times
{n,m} At least n times and at most m times are matched. Both m and n are non-negative integers, where n<=m.
\d Find the number
\s Finding whitespace characters
\b Matching word boundaries
[xyz] Collection of characters. Matches any of the contained characters
[a-z] Character range. Matches any character in the specified range. “[a-z]” can match any lowercase character from “A” to “Z”

Defining quantifiers is a string that matches occurrences of a certain number of times:

quantifiers describe
n+ Matches any string that contains at least one n and is greater than or equal to one time. For example, matching “h” in “Hello World”
n* Matches any string containing zero or more n’s that are not equal to one. For example, matching “ll” and “L” in “Hello World”
n? Matches any string containing zero or one n, 0, or 1

6. Write regular expressions

Regular basic syntax: “^([]{})([]{})([]{})$”; Regular string = “Start ([contain content]{length}) ([contain content]{length}) ([contain content]{length}) end”; Here are some of the easier regular expressions to create directly with a slash:

<script>
    // Matches a numeric character
    let re = /^\d$/;
    
    // The value contains at least four digits
    let re1 = /^\d{4,}$/;
    
    // The value contains 4 to 8 digits
    let re2 = / ^ \ d {4, 8} $/;
    
    // Matches a word character including an underscore
    let re3 = /^\w$/;
    
    // Matches four or more word characters
    let re4 = /^\w{4,}$/;
    
    // Contains 4 to 8 characters
    let re5 = {4, 8} $/ ^ \ w /;
</script>
Copy the code

These are some of the more complex regular expression applications. In fact, they are extensions of simple regular expressions. The principle is the same. If meet your needs can be directly copied and pasted use:

^ 1. Verify the user name and password: "[a zA - Z] \ w {5, 15} $") the correct format:" [a-z] [a-z] _ [0-9] ", and the first word must be for 6 ~ 16 2 letters. Verification number: (" ^ (\ d {3, 4} -) \ d {7, 8} $") the correct format: XXX XXXX - XXXXXXX/XXXXXXXX 3. Verify the phone number (including the virtual number segment) and the new number: "^ 1 ([38] [0-9] [5-9] | | 4 5 [0, 3, 5-9] 66 7 (0 to 8) | | | 9 [89]) [0-9] {8} $" 4. Verify identification number (15) : "\ d {and} [[0-9], 0-9 xx]", (18) : "\ d {and} (\ d | | X X)" 5. Verify Email address: (" ^ \ w + (\ w + / - +.]) * @ \ w + ([-] \ w +) * \ \ w + ([-] \ w +) * $") 6. The value contains only 26 letters and digits :("^[a-za-z0-9]+$") 7. Integer or decimal: ^[0-9]+([.][0-9]+){0,1}$8. Enter only n digits: "^\d{n}$" 10. Can only enter a number at least n: "^ \ d {n,} $11. Can only enter a number m ~ n bit:" ^ \ d {m, n} $" 12. Can only enter the number of zero and non-zero start: "^ (0 | [1-9] [0-9] *) $" 13. Only positive real numbers with two decimal places can be entered: "^[0-9]+(\.[0-9]{2})? $" 14. Enter only positive real numbers with 1 to 3 decimal places: "^[0-9]+(\.[0-9]{1,3})? $" 15. Enter only non-zero positive integers: "^\+? [1-9][0-9]*$" 16. Enter only non-zero negative integers: "^\-[1-9][0-9]*$" 17. Can only enter length is 3 characters: "^. {3} $18." only input string composed of 26 English letters: "^ [A Za - z] + $" 19. The value contains only 26 uppercase letters: "^[a-z]+$" 20. The value contains only 26 lowercase letters: "^[a-z]+$" 21. Verify if it contains ^%&',; =? $\ "characters, such as:" [% & ',; =? $\ \ ^] + "22. Only can input Chinese characters:" ^ [\ u4e00 - \ u9fa5] {0} $23." Verify URL: "^http://([\w-]+\.) +[\w-]+(/[\w-./?%&=]*)? $" 24. Verify 12 months of the year: "^(0? [1-9] | 1 [2-0]) $" correct format is: "01" ~ "09" and "10 ~ 12" 25. Verify 31 days of a month: "^((0? [1-9]) | | 2 (1) ([0-9]) | | 31) $30 "is the correct format for;" 01" ~ "09", 10" ~ "29" and 30 "~" 31 "26. Access to date a regular expression: "\ \ d {4} [| \ | - \.] \ d {12} \ 1 - \ [| \ - | \.] \ d {31} 1 - \ \ day?" "[a-za-z]+://[^\s]*" 32. Matching account whether legitimate (letter, allow 5-16 bytes, allow alphanumeric underlined) : "^ [a zA - Z] [a zA - Z0-9 _] {4, 15} $" 33. Match Tencent QQ id: "[1-9][0-9]{4,}" note: Tencent QQ id starts from 10 000 34. Match China zip code: "[1-9]\\d{5}(? ! \d)" note: China zip code is 6 digits 35. Match IP address: "([1-9]{1,3}\.) {3} [1-9] "note: to extract the useful IP address 36) matching MAC address:" ([A - Fa - f0-9] {2} \ {5}) [A - Fa - f0-9]"Copy the code

7. Common methods of regular expressions

7.1 Common Methods of String

1) The string method search() processes strings and returns the starting position of the search target string

// Snippets of code in HTML<body>
<p id="demo">The search() method handles strings and returns the position of the string:</p>
<script>
    let str = "hello world!";
    // Search for ll string, return 2
    let number = str.search("ll");
    document.getElementById("demo").innerHTML += number;
</script>
</body>
Copy the code

The browser running result is as follows:

2) The string method search() uses a regular expression to return the starting position of the search target string

// Snippets of code in HTML<body>
<p id="demo">The search() method handles the position of the regular expression return string:</p>
<script>
    let str = "hello world!";
    //ll is the pattern, I is the modifier, and performs case-insensitive matching
    // Search for ll string, return 2
    let number = str.search(/ll/i);
    document.getElementById("demo").innerHTML += number;
</script>
</body>
Copy the code

The browser running result is as follows:3) The string method replace() replaces the string

// HTML code snippets<body>
<p>Click the button on the replace() method to replace the string Hello with good</p>
<p id="demo">hello world!</p>
<input type="button" id="btn" value="Hit replace string">
<script>
    document.getElementById("btn").onclick = function () {
        // Replace the hello string with good and return the replaced string
        let text = document.getElementById("demo").innerText;
        // Call the replace method
        let s = text.replace("hello"."good");
        // Insert the returned string
        document.getElementById("demo").innerHTML = s;
    }
</script>
</body>
Copy the code

Browser running results:

No click:After clicking the button:

4) Use regular expressions in the string method replace()

// HTML code snippets<body>
<p>The button replace() method replaces the string Hello with good using a regular expression</p>
<p id="demo">hello world!</p>
<input type="button" id="btn" value="Hit replace string">
<script>
    document.getElementById("btn").onclick = function () {
        // Get the string
        let text = document.getElementById("demo").innerText;
        // Write the replaced string regular expression
        let l = /hello/i;
        // Call the replace method, which returns the replaced string
        let s = text.replace(l,"good");
        // Insert the returned string
        document.getElementById("demo").innerHTML = s;
    }
</script>
</body>
Copy the code

Browser running results:

No click:After clicking the button:

7.2 Common methods of RegExp regular objects

1) Test () is a regular expression method. It searches the string by pattern and returns true or false based on the result.

Example:

<body>
<p>The re object test() method searches for the "world" string in the following string</p>
<p id="demo">hello world!</p>
<p id="result"></p>
<script>
        // Get the string
        let text = document.getElementById("demo").innerText;
        // Create regular objects and regular expressions
        let reg = new RegExp(/world/i);
        // Call the test method instead and return a Boolean
        let result = reg.test(text);
        // Insert the returned string
        document.getElementById("result").innerHTML = result;
</script>
</body>
Copy the code

Results:

2) The exec() method is a regular expression method. It searches the string by the specified pattern and returns the found text. Example:

<body>
<p>The regular object exec() method searches for a "wor" string in the following string</p>
<p id="demo">hello world!</p>
<p id="result"></p>
<script>
        // Get the string
        let text = document.getElementById("demo").innerText;
        // Create regular objects and regular expressions
        let reg = new RegExp(/wor/i);
        // Call the exec method instead and return the searched text
        let result = reg.exec(text);
        // Insert the returned string
        document.getElementById("result").innerHTML = result;
</script>
</body>
Copy the code

Results:

8. To summarize

Learning regular expression is a face meng force at the beginning, like looking at the book of heaven, what TMD a string of symbols, in some regular expression foundation and practice after a further grasp, there are many shortcomings, please comment on the message. Write this blog to record the process of learning regular expressions, convenient for yourself and everyone