Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop all the elements that match the regex?

People also ask

How do I find all matches in regex?

To find find all the matches of a regular expression in this string in JavaScript, call match() method on this string, and pass the regular expression as argument. match() method returns an array of strings containing all the matches found for the given regular expression, in this string.

Can you loop in regex?

Using RedExp Loop you can find all entries of a phrase you seek in a text and process them in a loop. A phrase mask is specified by a regular expression. The search result of every iteration is saved in a variable as a standard comma-separated string.

How do I match a regex pattern?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

How do I allow all items in regex?

Throw in an * (asterisk), and it will match everything. Read more. \s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s ) will match anything that is not a whitespace character.


var reg = /e(.*?)e/g;
var result;
while((result = reg.exec(targetText)) !== null) {
    doSomethingWith(result);
}

Three approaches depending on what you want to do with it:

  • Loop through each match: .match

    targetText.match(/e(.*?)e/g).forEach((element) => {
       // Do something with each element
    });
    
  • Loop through and replace each match on the fly: .replace

    const newTargetText = targetText.replace(/e(.*?)e/g, (match, $1) => {
      // Return the replacement leveraging the parameters.
    });
    
  • Loop through and do something on the fly: .exec

    const regex = /e(.*?)e/g;  // Must be declared outside the while expression, 
                               // and must include the global "g" flag.
    
    let result;
    while(result = regex.exec(targetText)) {
      // Do something with result[0].
    } 
    

Try using match() on the string instead of exec(), though you could loop with exec as well. Match should give you the all the matches at one go. I think you can omit the global specifier as well.

reg = new RegExp(/e(.*?)e/);   
var matches = targetText.match(reg);

targetText = "SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext"    
reg = new RegExp(/e(.*?)e/g);   
var result;
while (result = reg.exec(targetText))
{
    ...
}