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

The most commonly used HTML escape sequence

In HTML, <, >, &, etc. have special mean...

The use of anchor points in HTML_PowerNode Java Academy

Now let's summarize several situations of con...

VMware Workstation virtual machine installation operation method

Virtual machines are very convenient testing soft...

How to create a MySQL database (de1) using commands

1. Connect to MYSQL Format: mysql -h host address...

JavaScript to achieve simple drag effect

This article shares the specific code of JavaScri...

Detailed explanation of common usage methods of weixin-js-sdk in vue

Link: https://qydev.weixin.qq.com/wiki/index.php?...

Detailed explanation of firewall rule settings and commands (whitelist settings)

1. Set firewall rules Example 1: Expose port 8080...

Detailed explanation of TS object spread operator and rest operator

Table of contents Overview Object rest attribute ...

Three notification bar scrolling effects implemented with pure CSS

Preface The notification bar component is a relat...

Summary of Linux user groups and permissions

User Groups In Linux, every user must belong to a...

What do CN2, GIA, CIA, BGP and IPLC mean?

What is CN2 line? CN2 stands for China Telecom Ne...

Vue implements graphic verification code

This article example shares the specific code of ...

Solution to the failure of 6ull to load the Linux driver module

Table of contents 0x01 Failed to load the driver ...

Example of implementing TikTok text shaking effect with CSS

In daily development, front-end students often ar...

Steps to install superset under win10 system

Superset is a lightweight self-service BI framewo...