A few days ago, we encountered a regular expression problem matching IP address, as shown in the figure belowMatching problem in JS regular expression

The variable re in the figure is the regular expression of the variable IP, but why is the same match true and false?

lastIndex

After looking at some methods of regular expression, we find that there is a lastindex, which indicates that the next match starts from the character of the string, and the initial value is 0; when I use the global G. If the matching is successful, lastindex becomes the position after the matching string. If the matching is not successful, lastindex is reset to 0. Lastindex is a property of regular object, and does not care whether the string is the same. Therefore, even if the matching string changes, lastindex will not be cleared. As shown in the figure belowMatching problem in JS regular expression

Problem solving

Finally, if I remove the global g, as shown in the figure belowMatching problem in JS regular expression

Yes, thank you for reading