Regular expressions - it's not that hard

Keywords: Javascript Front-end regex

        Many people's first reaction when they see regular expressions is that they have a big head and are difficult to learn. They have such a long string of symbols. What is this. Ah! Don't worry. In fact, regular expressions are easy to understand step by step. Don't believe it? Look!

catalogue

1, What is a regular expression

1. General

2. Function

3. Tools

2, Use of regular expressions

1. Create

Method 1: create by calling the constructor of RegExp object

Method 2: create regular expressions with literal values

2. Test

test() method

exec() method

match() method

3, Special characters of regular expressions

1. Boundary character

2. Character class

2.1 [] square brackets

2.2 quantifier

3. Predefined classes

4, Regular substitution

1, What is a regular expression

1. General

         Regular Expression is a text pattern used to match character combinations in a string. In JavaScript, regular expressions are also objects. Including ordinary characters and special characters.

2. Function

         Regular tables are often used to retrieve and replace text that conforms to a pattern (rule). For example, validation form: only English letters, numbers or underscores can be entered in the user name form, and Chinese (matching) can be entered in the nickname input box. In addition, regular expressions are often used to filter out some sensitive words in the page content (replacement), or get the specific part we want from the string (extraction), etc.

3. Tools

        Regular expression online testing tool is used to help us test whether the written regular expression can correctly match the text.

        Regular expression online testing | rookie tool       

          The tool also provides us with common regular expression writing methods, which can be directly used in development to improve efficiency!

2, Use of regular expressions

1. Create

         In JavaScript, you can create a regular expression in two ways.

  • Method 1: create by calling the constructor of RegExp object

var regexp = new RegExp(/123/);
console.log(regexp);
  • Method 2: create regular expressions with literal values

 var rg = /123/;    // Recommended method

2. Test

  • test() method

        test() checks whether the string conforms to the rules. The return value is of boolean type, and its parameter is the test string.

var rg = /123/;
console.log(rg.test(123));//Whether 123 appears in the matching character, and the result is true
console.log(rg.test('abc'));//Whether 123 appears in the matching character. If it does not appear, the result is false
  • exec() method

        eexc() returns an array of length 1 if the string conforms to the regular rules. The first substring conforming to the rule is stored in the array. If it is a global match, when the same regular rule is used to match the same string multiple times, the starting position of each time is the last lastindex position. The length of the array returned each time is still 1.

var str = "1a1b1c";
var reg = /1./g;
console.log(reg.exec(str)[0]); // 1a
console.log(reg.exec(str)[0]); // 1b
console.log(reg.exec(str)[0]); // 1c

         The starting position where the matching string is stored in index;   lastIndex: the end position of the substring conforming to the rule; input: save str  

  • match() method

        The match() method is similar to the exec() method. When it is not a global match, this method is the same as exec(). After using global match, all qualified strings will be returned at one time.

var str = "1a1b1c";
var reg = /1./g;
console.log(str.match(reg));// [1a,1b,1c]

3, Special characters of regular expressions

        A regular expression can consist of simple characters, such as / 123 /, or a combination of simple characters and special characters, such as / ab*c /. Special characters, also known as metacharacters, are special symbols with special significance in regular expressions, such as ^, $, + and so on.

         There are many special characters. You can refer to: Regular expression - JavaScript | MDN

1. Boundary character

        Function: mainly used to prompt the position of characters.

Boundary characterexplain
^Represents the text that matches the beginning of the line (starting with who)
$

Represents the text that matches the end of the line (with whom)

          If ^ and $are together, it means that it must be an exact match.

var rg = /abc/; // Regular expressions do not need quotation marks, whether numeric or string
// /abc / as long as abc is included, the string returns true
console.log(rg.test('abc'));   // true
console.log(rg.test('abcd'));  // true
console.log(rg.test('aabcd')); // true
------------------------------------------------------------------------------------

var reg = /^abc/;
console.log(reg.test('abc'));   // true
console.log(reg.test('abcd'));  // true
console.log(reg.test('aabcd')); // false
------------------------------------------------------------------------------------

var reg1 = /^abc$/; // Exact matching requires an abc string to meet the specification
console.log(reg1.test('abc'));    // true
console.log(reg1.test('abcd'));   // false
console.log(reg1.test('aabcd'));  // false
console.log(reg1.test('abcabc')); // false    

2. Character class

2.1 [] square brackets

         Function: there are a series of characters to choose from. Just match one of them

var rg = /[abc]/; // It returns true as long as it contains a, b or c
console.log(rg.test('apple'));//true
console.log(rg.test('red'));//false
----------------------------------------------------------------------------------

var rg = /^[abc]$/; // Choose one from three. Only the letters a, b or c return true
console.log(rg.test('aa'));//false
console.log(rg.test('a'));//true
console.log(rg.test('abc'));//true
----------------------------------------------------------------------------------

var rg = /^[a-z]$/ //26 English letters. Any letter returns true - indicating the range from a to z  
console.log(rg.test('a'));//true
console.log(rg.test('z'));//true
console.log(rg.test('A'));//false
-----------------------------------------------------------------------------------

//Character combination
var rg = /^[a-zA-Z0-9]$/; // 26 English letters (both uppercase and lowercase) any letter returns true  
------------------------------------------------------------------------------------

//The addition of ^ inside the inverted square brackets indicates negation. As long as the characters in the square brackets are included, false is returned.
var rg = /^[^a-zA-Z0-9]$/;
console.log(rg.test('a'));//false
console.log(rg.test('Z'));//false
console.log(rg.test(7));//false
console.log(rg.test('!'));//true

2.2 quantifier

         Function: quantifier is used to set the number of times a pattern appears.

classifier  explain            
*Repeat 0 or more times
+Repeat 1 or more times
?Repeat 0 or 1 times
{n}{n} Repeat n times
{n,}Repeat n or more times
{n,m}Repeat n to m times

         

         In this way, we can write a complete regular expression for form verification ~ here is a small dom

 var username = document.getElementById("username");
        var qq = document.getElementById("qq");
        var span = document.querySelector("li").querySelector("span");
        // userreg = /\W/;
        var userreg = /^[a-zA-Z0-9]{6,16}$/;
        var qqreg = /^[1-9]{1}\d{4,9}$/
        reg(username, userreg);
        reg(qq, qqreg);
        function reg(ele, reg) {
            ele.onblur = function () {
                if (reg.test(this.value)) {
                    // console.log('zhengque');
                    this.nextElementSibling.className = "right"
                    this.nextElementSibling.innerHTML = "Correct input"
                } else {
                    // console.log('cuowu');
                    this.nextElementSibling.className = "wrong"
                    this.nextElementSibling.innerHTML = "Input error, please re-enter"
                }
            }
        }

  To sum up:

        Usage guide for three kinds of parentheses in regular expressions:

Bracket typemeaning
BracesQuantifier, indicating the number of repetitions inside
BracketA character set that matches any character in parentheses
parenthesespriority

3. Predefined classes

        Function: predefined classes refer to the abbreviations of some common patterns.

Scheduled classexplain
\dMatch any number between 0-9, equivalent to [0-9]
\DMatch all characters other than 0-9, equivalent to [^ 0-9]
\w

Match any letters, numbers and underscores, equivalent to [A-Za-z0-9]

\WCharacters other than letters, numbers, and underscores are equivalent to [^ A-Za-z0-9]
\sMatch spaces (including line breaks, tabs, spaces, etc.), equivalent to [\ t\r\n\v\f]
\SMatches characters other than spaces, equivalent to [^ \ t\r\n\v\f]

4, Regular substitution

        When we need to replace the content (string) in development, we can use the replace() method. This method can realize the operation of replacing the string, and the parameters used to replace can be a string or a regular expression.

        When we want global replacement, we need to add g after the regular expression; otherwise, we only replace the first qualified character or string; when we want to be case insensitive, we need to add i after the regular expression. Multiple replacement conditions are separated by '|'

  var str = 'cqyzsC012QzAabcd';
        var newstr = str.replace(/[acq]/gi, 'Hello')
        console.log(newstr); //Hello, yzs Hello, 012 Hello, z Hello, b Hello, d

        In fact, looking at the whole article, regular expressions are not difficult, and the writing method of regular expressions is not unique. You only need to help us verify whether the input content can match correctly. The tools also help us write common regular expressions. You can also use tools if necessary~

        After reading this blog, regular expression is a big move to win!

Posted by Crysma on Fri, 03 Dec 2021 13:41:57 -0800