Multiple values on regular expression

Hi Team,

How to capture multiple values with regular expression. The below regex (myRegex1) shows multiple values while testing with the online regex validators. But when I tried on K6, it capture only the first one.

Guide me on this

Hi @Gerard !
See this answer. Example:

match = new RegExp( (.*?) (.*?)
 ).exec(response.body);

Now match is an array of two groups - match[0] and match[1]

Hi @PaulM

The above-mentioned regex ( myRegex1) can be found in 7 places on the response body. If I run the regex it captures only the first one and the other 7 places it skips.

@Gerard, try to use this code:

export default function () {

  let str = '<h1>Hello, world!</h1><h1>Hello, world!</h1><h1>Hello, world!</h1><h1>Hello, world!</h1>';
let regexp = 'Hello, world!';
let matchAll = str.matchAll(regexp);

      for (let value of matchAll) {     
        console.log(value);
      }
}
Output:
INFO[0000] Hello, world!                                 source=console
INFO[0000] Hello, world!                                 source=console
INFO[0000] Hello, world!                                 source=console
INFO[0000] Hello, world!                                 source=console

There is additional information on the matchAll function here.

1 Like

Hi @PaulM

I getting an error while using matchAll.
image

image

Console output
image

@Gerard The result of matchAll() is an object - RegExp String Iterator. If need an array, then you need to do this:
coverImages = Array.from(coverImages);