Skip to content
the poor coder

regex exec fails twice

Poor Man
Published
Reading time
2 min read
On this page

Why Regex Exec Fails Twice?#

Regex or Regular Expressions is a powerful tool for searching, finding and manipulating text data. It can be used in many programming languages to perform various operations on strings. However, sometimes regex exec fails twice, which can cause confusion among developers. Let's explore some possible reasons for this issue.

1. Global Flag not set#

The most common reason for regex exec failing twice is that the global flag is not set. By default, the regex engine stops after finding the first match. If you want to find all matches in a string, you need to set the global flag. Here's an example:

Text

    const regex = /hello/g;
    const str = 'hello world, hello universe';
    let match;
    
    while (match = regex.exec(str)) {
      console.log(match[0], match.index);
    }
  

2. lastIndex not reset#

Another reason for regex exec failing twice is that the lastIndex property is not reset. The lastIndex property specifies the index at which to start the next search. If you don't reset it, the regex engine will start searching from the previous index and may miss some matches. Here's an example:

Text

    const regex = /hello/g;
    const str = 'hello world, hello universe';
    let match;
    
    while (match = regex.exec(str)) {
      console.log(match[0], match.index);
      regex.lastIndex = match.index + 1;
    }
  

3. Incorrect Regex Pattern#

One more reason for regex exec failing twice is that the regex pattern is incorrect. This can happen if you don't escape special characters or use incorrect syntax. In such cases, the regex engine may not find any matches or miss some matches. Here's an example:

Text

    const regex = /hello\sworld/g; // \s matches whitespace
    const str = 'hello       world, hello universe';
    let match;
    
    while (match = regex.exec(str)) {
      console.log(match[0], match.index);
    }
  

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC