A record of pitfalls in JS regular matching

A record of pitfalls in JS regular matching

I recently discovered a pitfall in regular expression matching in JS, and it was so strange at the time that I even suspected that something paranormal was going on.

The following is the pit code

   var str=["二七1","二七2","金水","二七3","二七4","二七5"]
        var reg = new RegExp ("二七", "g");
        for(var i=0;i<str.length;i++){
            if(reg.test(str[i])){
                console.log(str[i])
            }
        }

I use regular expression to globally match str, and print it out when it is satisfied, so I get this

There are two missing for no apparent reason, and I will make a separate judgment on them.

      var str=["二七1","二七2","金水","二七3","二七4","二七5"]
        var reg = new RegExp ("二七", "g");
        for(var i=0;i<str.length;i++){
            if(reg.test(str[i])){
                console.log(str[i])
            }
            if(i==1){
                console.log(reg.test(str[i]))
            }
            if(i==4){
                console.log(reg.test(str[i]))
            }
        }

So I got this

One more is missing, but I can see that the two missing ones satisfy the regularity check. Then I found the following passage on the Internet:

If a string is successfully matched in a regular expression, lastIndex will be set to the position of the first matched string as the starting point for the next search of the string global match. If subsequent fields can be matched successfully, lastIndex will be repeatedly reassigned until the match fails, and it will be reset to 0.

But I asked my teacher, and he told me that after the match is found, lastIndex+1 is returned. That is, when I matched for the first time, lastIndex was 2. This 2 is the subscript in the string, not the subscript of the array. Therefore, when judging str[1], it starts from the string subscript 2, not from 0. Therefore, the second judgment is false, and the match fails. LastIndex is set to 0, so the third match can be successful.

So after the judgment result is true, lastIndex is set to 0, so that the data is normal.

The data is normal.

Summarize

If global matching is used, then lastIndex is set to zero after each search, or global matching is not used and direct matching can be performed.

Here is a summary of netizens:

lastIndex literally means the last index. In fact, it means the index position where the regular expression starts the next search. It is always 0 for the first time. When the first search is completed, the value of lastIndex will be set to the index position of the last character of the matched string plus 1. The second search will start from the lastIndex position, and so on. If not found, lastIndex is reset to 0. It should be noted that the lastIndex attribute only works in a regular expression with a global flag. If we remove the g flag from the regular expression in the above code, then all three pop-ups will be true.

Friends in need can refer to it. This is the end of this article about a record of JS regular matching pitfalls. For more relevant JS regular matching pitfalls, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • js regular expression learning notes: matching strings
  • Regular matching password can only be a combination of numbers and letters [PHP and JS implementation]
  • String string matching javascript regular expression
  • JS regular learning notes: matching string literals
  • JavaScript regular expression matching string literals
  • JS regular learning notes: Matching string literal optimization

<<:  MySQL knowledge points and commonly used MYSQL commands for the second-level computer exam

>>:  Detailed explanation of three ways to cut catalina.out logs in tomcat

Recommend

How to create a test database with tens of millions of test data in MySQL

Sometimes you need to create some test data, base...

Example of creating a virtual host based on Apache port

apache: create virtual host based on port Take cr...

Vue implements three-level navigation display and hiding

This article example shares the specific code of ...

Implementation of new issues of CSS3 selectors

Table of contents Basic Selector Extensions Attri...

Summary of using the reduce() method in JS

Table of contents 1. Grammar 2. Examples 3. Other...

Vue echarts realizes horizontal bar chart

This article shares the specific code of vue echa...

Three ways to communicate between React components (simple and easy to use)

Table of contents 1. Parent-child component commu...

Native JS encapsulation vue Tab switching effect

This article example shares the specific code of ...

How to solve the problem of blurry small icons on mobile devices

Preface Previously, I talked about the problem of...

Methods and techniques for designing an interesting website (picture)

Have you ever encountered a situation where we hav...

Implementation steps for installing Redis container in Docker

Table of contents Install Redis on Docker 1. Find...

How to open the port in Centos7

The default firewall of CentOS7 is not iptables, ...

Handwritten Vue2.0 data hijacking example

Table of contents 1: Build webpack 2. Data hijack...

JavaScript to achieve calendar effect

This article shares the specific code for JavaScr...