1

I'm trying to find all the matches in a string that follow a particular pattern like this {{any thing here}}, but I'm not able to extract all the matches properly. Don't know what I'm doing wrong. Below is the code that I have tried so far.

const string = `You have been identified in <span class="alert underline">{{db.count}}</span> breaches with <span class="alert underline">{{db.data_types}}</span> unique data types.`;

I have tried the following methods:

Method 1

const matches = /{{(.*?)}}/igm.exec(value);
console.log(matches);

Output:

{
    0: "{{db.count}}",
    1: "db.count",
    index: 58,
    input: "You have been identified in <span class="alert und…line">{{db.data_types}}</span> unique data types.",
    groups: undefined
}

Method 2

const matches = RegExp('{{(.*?)}}', 'igm').exec(value);
console.log(matches);

Output:

{
    0: "{{db.count}}",
    1: "db.count",
    index: 58,
    input: "You have been identified in <span class="alert und…line">{{db.data_types}}</span> unique data types.",
    groups: undefined
}

Method 3

const matches = value.match(/{{(.*?)}}/igm);
console.log(matches);

Output:

[
    "{{db.count}}",
    "{{db.data_types}}"
]

Expected output:

[
    'db.count',
    'db.data_types'
]

If anyone has faced the same issue, please help. Thanks in advance.

Rohit Khatri
  • 1,980
  • 3
  • 25
  • 45
  • You need to repeatedly apply `exec` to get all of the matches, as demonstrated in the RegExp docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec – Hunter McMillen Aug 22 '18 at 12:53

3 Answers3

2

If you want to find all matches, you'll have to use exec() in a loop.

Example:

const string = `You have been identified in <span class="alert underline">{{db.count}}</span> breaches with <span class="alert underline">{{db.data_types}}</span> unique data types.`;

let regEx = /{{(.*?)}}/igm;
let result;

while ((result = regEx.exec(string)) !== null) {
    console.log(result[1]);
}
0

Your method 3 looks good. I would try this regex to not-match the curly braces:

[^{}]+(?=}})
Tim Klein
  • 2,538
  • 15
  • 19
  • It's not efficient, It's adding extra array elements, here's the response ```["leaked_databases.breach_count", "", "leaked_databases.data_types_count", ""]``` – Rohit Khatri Aug 22 '18 at 13:01
  • You're right, I updated the answer to use a better quantifier (`+`: one or more non-curly brace). – Tim Klein Aug 22 '18 at 17:13
0

Grouping does not play well with the /g (global) flag, See here. @fragezeichen gave the right solution (also documented in the link)

Meir
  • 14,081
  • 4
  • 39
  • 47