Search code examples
javascriptregexregex-group

Issue with getting the first matching item and its index position from a regex matching a string ( javascript)


I've written a regex that matches all the function names in a string

Regex :- /([a-zA-Z ]*(?=\())/g
String:- (( MAX(1,2,3,4), min(1,2,3), max(3,4,5)))

Above regex matches all the function names by checking for a a bunch of words followed by "(". In this case the matches are MAX, MIN, MAX ( apart from some empty strings which I am filtering using match.filter(String). )

In one of my conditions I only need the "FIRST" Matching function along with its START and STOP index. So, I wrote the following function to get it.

var re = /([a-zA-Z ]*(?=\())/g;    
var str = "max(1,2), min(1,2)";

while ((match = re.exec(str)) !== null) {
    console.log("match found at " + match.index);
  // Pick the first matching index from here ? 
}

But this is going into an infinte loop and it's not giving the desired output ( I am sure something is wrong with the function above, but not quite sure what ).

Example string2 = (((( max(34234,234234,344) min(1,2,3)))))*23 + max(23434, 234234,234234)))  - I only need the first matching function "max" from here along with it's start and stop index's.

Solution

  • Following solution expects the pattern you provided (specifically spaces before and after function.)

    The .match() method provides an index for the start position and use the .length property of the string to get the end position:

    let string = '(((( max(34234,234234,344) min(1,2,3)))))*23 + max(23434, 234234,234234)))';
    let result = '';
    while (result != null) {
      result = string.match(/\w+(?=\()/);
      if (result != null) {
        console.log('Found: ' + result, 'Start: ' + result.index, 'End: ' + parseInt(result[0].length + result.index));
      }
      string = string.split(result)[1];
    }