Using regex with multiple groups

How can we select specific regex group in k6?

In the below regex we have 4 groups, so how I need to select each group and assign it to a variable?

    match = new RegExp(
      "\\/\\/View Product event\\s+tracker\\.setEcommerceView\\('(.*?)',  \\/\\/ \\(required\\) SKU: Product unique identifier\\s+'(.*?)',  \\/\\/ \\(optional\\) Product name\\s+\\['(.*?)'\\],  \\/\\/ \\(optional\\) Product category, or array of up to 5 categories\\s+'(.*?)'\\);"
    ).exec(response.body);

    vars["cp_productId"] = match ? match[1] || match[0] : null;

Hi @divinp ,

as per the Regexp.prototype.exec documentation the first index of the result is the whole match and then each next index is the corresponding group so in your case match[4] will be w/e the 4th group matched.

For example:

var match = new RegExp(
      "aaaa(ab+) something ([^ ])+ here is a (third) and a (forth match .+) end."
    ).exec("aaaaaaabbbbb something else here is a third and a forth match with something until the end.");

console.log(JSON.stringify(match, null, "  "));`

will print

[
  "aaaaabbbbb something else here is a third and a forth match with something until the end.",
  "abbbbb",
  "e",
  "third",
  "forth match with something until the"
] 

Hope this helps you

@mstoykov Could you please let me know, how will I assign these matches to a variable?

The same way you will do that for anythign else

let variablename = match[4]; // possibly with the `let ` if it's already defined
1 Like

How can we set ordinal position in regex ?

@mstoykov could you please look into this

Can you expand on your question as I don’t understand what you are trying to do

@mstoykov : Lets say for a particular match there are 3 occurrence:
Like

  1. Test1
  2. Test2
  3. Test3

And I need to fetch the 3rd value or 3rd ordinal position, so how can I obtain that?

Along with this I would like to know how can we fetch a random value from all the occurrence?

You likely want to use matchAll.

The last few questions are generic javascript questions, so just using google and maybe asking them in places with javascript developers will be enough, no need to ping me to answer a non k6 centric question :slight_smile: