-1

I'm currently generating a regex statement for a string comparing program I'm writing for my Discord bot. I am using the following generated regex string:

let regex = new RegExp("(TRIGGER WORD) (.*?)", "g");

I then execute it using the following:

let returns = regex.exec("TRIGGER WORD WHAT");

I get the following:

 [ 'stud, ', 'stud,', '', index: 0, input: 'stud, what' ]

Which has no indication of grouping for 'WHAT' which I am trying to get most importantly.

From a background in PHP, I am expecting that I will get an array back such as the following:

 ['TRIGGER WORD', 'WHAT']
Jack Hales
  • 1,574
  • 23
  • 51

1 Answers1

3

In your regex, the last part (.*?) is lazy and will repeat the dot as few times as possible.

For your example data you could match the quantifier in the second group greedy (.*). Your results are in capturing group 1 and 2.

This will match TRIGGER WORD in the first group, a whitespace and what is following in the second group.

let regex = new RegExp("(TRIGGER WORD) (.*)", "g");
let returns = regex.exec("TRIGGER WORD WHAT");
console.log(returns);
console.log(returns[1]);
console.log(returns[2]);
The fourth bird
  • 154,723
  • 16
  • 55
  • 70